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
google/walt
android/WALT/app/src/main/java/org/chromium/latency/walt/programmer/Programmer.java
// Path: android/WALT/app/src/main/java/org/chromium/latency/walt/SimpleLogger.java // public class SimpleLogger { // private static final String LOG_INTENT = "log-message"; // public static final String TAG = "WaltLogger"; // // private static final Object LOCK = new Object(); // private static SimpleLogger instance; // // private StringBuilder sb = new StringBuilder(); // private LocalBroadcastManager broadcastManager; // // public static SimpleLogger getInstance(Context context) { // synchronized (LOCK) { // if (instance == null) { // instance = new SimpleLogger(context.getApplicationContext()); // } // return instance; // } // } // // private SimpleLogger(Context context) { // broadcastManager = LocalBroadcastManager.getInstance(context); // } // // public synchronized void log(String msg) { // Log.i(TAG, msg); // sb.append(msg); // sb.append('\n'); // if (broadcastManager != null) { // Intent intent = new Intent(LOG_INTENT); // intent.putExtra("message", msg); // broadcastManager.sendBroadcast(intent); // } // } // // public void registerReceiver(BroadcastReceiver broadcastReceiver) { // broadcastManager.registerReceiver(broadcastReceiver, new IntentFilter(LOG_INTENT)); // } // // public void unregisterReceiver(BroadcastReceiver broadcastReceiver) { // broadcastManager.unregisterReceiver(broadcastReceiver); // } // // public String getLogText() { // return sb.toString(); // } // // public void clear() { // sb = new StringBuilder(); // } // // } // // Path: android/WALT/app/src/main/java/org/chromium/latency/walt/WaltConnection.java // public interface WaltConnection { // // void connect(); // // boolean isConnected(); // // void sendByte(char c) throws IOException; // // int blockingRead(byte[] buffer); // // RemoteClockInfo syncClock() throws IOException; // // void updateLag(); // // void setConnectionStateListener(ConnectionStateListener connectionStateListener); // // interface ConnectionStateListener { // void onConnect(); // void onDisconnect(); // } // }
import android.content.Context; import android.os.Handler; import android.util.Log; import org.chromium.latency.walt.R; import org.chromium.latency.walt.SimpleLogger; import org.chromium.latency.walt.WaltConnection; import java.io.InputStream; import java.text.ParseException; import java.util.Arrays;
/* * Copyright (C) 2016 The Android Open Source Project * * 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.chromium.latency.walt.programmer; public class Programmer { private static final String TAG = "Programmer";
// Path: android/WALT/app/src/main/java/org/chromium/latency/walt/SimpleLogger.java // public class SimpleLogger { // private static final String LOG_INTENT = "log-message"; // public static final String TAG = "WaltLogger"; // // private static final Object LOCK = new Object(); // private static SimpleLogger instance; // // private StringBuilder sb = new StringBuilder(); // private LocalBroadcastManager broadcastManager; // // public static SimpleLogger getInstance(Context context) { // synchronized (LOCK) { // if (instance == null) { // instance = new SimpleLogger(context.getApplicationContext()); // } // return instance; // } // } // // private SimpleLogger(Context context) { // broadcastManager = LocalBroadcastManager.getInstance(context); // } // // public synchronized void log(String msg) { // Log.i(TAG, msg); // sb.append(msg); // sb.append('\n'); // if (broadcastManager != null) { // Intent intent = new Intent(LOG_INTENT); // intent.putExtra("message", msg); // broadcastManager.sendBroadcast(intent); // } // } // // public void registerReceiver(BroadcastReceiver broadcastReceiver) { // broadcastManager.registerReceiver(broadcastReceiver, new IntentFilter(LOG_INTENT)); // } // // public void unregisterReceiver(BroadcastReceiver broadcastReceiver) { // broadcastManager.unregisterReceiver(broadcastReceiver); // } // // public String getLogText() { // return sb.toString(); // } // // public void clear() { // sb = new StringBuilder(); // } // // } // // Path: android/WALT/app/src/main/java/org/chromium/latency/walt/WaltConnection.java // public interface WaltConnection { // // void connect(); // // boolean isConnected(); // // void sendByte(char c) throws IOException; // // int blockingRead(byte[] buffer); // // RemoteClockInfo syncClock() throws IOException; // // void updateLag(); // // void setConnectionStateListener(ConnectionStateListener connectionStateListener); // // interface ConnectionStateListener { // void onConnect(); // void onDisconnect(); // } // } // Path: android/WALT/app/src/main/java/org/chromium/latency/walt/programmer/Programmer.java import android.content.Context; import android.os.Handler; import android.util.Log; import org.chromium.latency.walt.R; import org.chromium.latency.walt.SimpleLogger; import org.chromium.latency.walt.WaltConnection; import java.io.InputStream; import java.text.ParseException; import java.util.Arrays; /* * Copyright (C) 2016 The Android Open Source Project * * 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.chromium.latency.walt.programmer; public class Programmer { private static final String TAG = "Programmer";
private SimpleLogger logger;
google/walt
android/WALT/app/src/main/java/org/chromium/latency/walt/programmer/Programmer.java
// Path: android/WALT/app/src/main/java/org/chromium/latency/walt/SimpleLogger.java // public class SimpleLogger { // private static final String LOG_INTENT = "log-message"; // public static final String TAG = "WaltLogger"; // // private static final Object LOCK = new Object(); // private static SimpleLogger instance; // // private StringBuilder sb = new StringBuilder(); // private LocalBroadcastManager broadcastManager; // // public static SimpleLogger getInstance(Context context) { // synchronized (LOCK) { // if (instance == null) { // instance = new SimpleLogger(context.getApplicationContext()); // } // return instance; // } // } // // private SimpleLogger(Context context) { // broadcastManager = LocalBroadcastManager.getInstance(context); // } // // public synchronized void log(String msg) { // Log.i(TAG, msg); // sb.append(msg); // sb.append('\n'); // if (broadcastManager != null) { // Intent intent = new Intent(LOG_INTENT); // intent.putExtra("message", msg); // broadcastManager.sendBroadcast(intent); // } // } // // public void registerReceiver(BroadcastReceiver broadcastReceiver) { // broadcastManager.registerReceiver(broadcastReceiver, new IntentFilter(LOG_INTENT)); // } // // public void unregisterReceiver(BroadcastReceiver broadcastReceiver) { // broadcastManager.unregisterReceiver(broadcastReceiver); // } // // public String getLogText() { // return sb.toString(); // } // // public void clear() { // sb = new StringBuilder(); // } // // } // // Path: android/WALT/app/src/main/java/org/chromium/latency/walt/WaltConnection.java // public interface WaltConnection { // // void connect(); // // boolean isConnected(); // // void sendByte(char c) throws IOException; // // int blockingRead(byte[] buffer); // // RemoteClockInfo syncClock() throws IOException; // // void updateLag(); // // void setConnectionStateListener(ConnectionStateListener connectionStateListener); // // interface ConnectionStateListener { // void onConnect(); // void onDisconnect(); // } // }
import android.content.Context; import android.os.Handler; import android.util.Log; import org.chromium.latency.walt.R; import org.chromium.latency.walt.SimpleLogger; import org.chromium.latency.walt.WaltConnection; import java.io.InputStream; import java.text.ParseException; import java.util.Arrays;
/* * Copyright (C) 2016 The Android Open Source Project * * 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.chromium.latency.walt.programmer; public class Programmer { private static final String TAG = "Programmer"; private SimpleLogger logger; private FirmwareImage image; private BootloaderConnection conn; private Context context; private Handler handler = new Handler(); public Programmer(Context context) { this.context = context; } public void program() { logger = SimpleLogger.getInstance(context); InputStream in = context.getResources().openRawResource(R.raw.walt); image = new FirmwareImage(); try { image.parseHex(in); } catch (ParseException e) { Log.e(TAG, "Parsing input file: ", e); } conn = BootloaderConnection.getInstance(context); // TODO: automatically reboot into the bootloader logger.log("\nRemember to press the button on the Teensy first\n");
// Path: android/WALT/app/src/main/java/org/chromium/latency/walt/SimpleLogger.java // public class SimpleLogger { // private static final String LOG_INTENT = "log-message"; // public static final String TAG = "WaltLogger"; // // private static final Object LOCK = new Object(); // private static SimpleLogger instance; // // private StringBuilder sb = new StringBuilder(); // private LocalBroadcastManager broadcastManager; // // public static SimpleLogger getInstance(Context context) { // synchronized (LOCK) { // if (instance == null) { // instance = new SimpleLogger(context.getApplicationContext()); // } // return instance; // } // } // // private SimpleLogger(Context context) { // broadcastManager = LocalBroadcastManager.getInstance(context); // } // // public synchronized void log(String msg) { // Log.i(TAG, msg); // sb.append(msg); // sb.append('\n'); // if (broadcastManager != null) { // Intent intent = new Intent(LOG_INTENT); // intent.putExtra("message", msg); // broadcastManager.sendBroadcast(intent); // } // } // // public void registerReceiver(BroadcastReceiver broadcastReceiver) { // broadcastManager.registerReceiver(broadcastReceiver, new IntentFilter(LOG_INTENT)); // } // // public void unregisterReceiver(BroadcastReceiver broadcastReceiver) { // broadcastManager.unregisterReceiver(broadcastReceiver); // } // // public String getLogText() { // return sb.toString(); // } // // public void clear() { // sb = new StringBuilder(); // } // // } // // Path: android/WALT/app/src/main/java/org/chromium/latency/walt/WaltConnection.java // public interface WaltConnection { // // void connect(); // // boolean isConnected(); // // void sendByte(char c) throws IOException; // // int blockingRead(byte[] buffer); // // RemoteClockInfo syncClock() throws IOException; // // void updateLag(); // // void setConnectionStateListener(ConnectionStateListener connectionStateListener); // // interface ConnectionStateListener { // void onConnect(); // void onDisconnect(); // } // } // Path: android/WALT/app/src/main/java/org/chromium/latency/walt/programmer/Programmer.java import android.content.Context; import android.os.Handler; import android.util.Log; import org.chromium.latency.walt.R; import org.chromium.latency.walt.SimpleLogger; import org.chromium.latency.walt.WaltConnection; import java.io.InputStream; import java.text.ParseException; import java.util.Arrays; /* * Copyright (C) 2016 The Android Open Source Project * * 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.chromium.latency.walt.programmer; public class Programmer { private static final String TAG = "Programmer"; private SimpleLogger logger; private FirmwareImage image; private BootloaderConnection conn; private Context context; private Handler handler = new Handler(); public Programmer(Context context) { this.context = context; } public void program() { logger = SimpleLogger.getInstance(context); InputStream in = context.getResources().openRawResource(R.raw.walt); image = new FirmwareImage(); try { image.parseHex(in); } catch (ParseException e) { Log.e(TAG, "Parsing input file: ", e); } conn = BootloaderConnection.getInstance(context); // TODO: automatically reboot into the bootloader logger.log("\nRemember to press the button on the Teensy first\n");
conn.setConnectionStateListener(new WaltConnection.ConnectionStateListener() {
google/walt
android/WALT/app/src/main/java/org/chromium/latency/walt/MainActivity.java
// Path: android/WALT/app/src/main/java/org/chromium/latency/walt/programmer/Programmer.java // public class Programmer { // private static final String TAG = "Programmer"; // private SimpleLogger logger; // // private FirmwareImage image; // private BootloaderConnection conn; // // private Context context; // private Handler handler = new Handler(); // // public Programmer(Context context) { // this.context = context; // } // // public void program() { // logger = SimpleLogger.getInstance(context); // InputStream in = context.getResources().openRawResource(R.raw.walt); // image = new FirmwareImage(); // try { // image.parseHex(in); // } catch (ParseException e) { // Log.e(TAG, "Parsing input file: ", e); // } // // conn = BootloaderConnection.getInstance(context); // // TODO: automatically reboot into the bootloader // logger.log("\nRemember to press the button on the Teensy first\n"); // conn.setConnectionStateListener(new WaltConnection.ConnectionStateListener() { // @Override // public void onConnect() { // handler.post(programRunnable); // } // // @Override // public void onDisconnect() {} // }); // if (!conn.isConnected()) { // conn.connect(); // } // } // // private Runnable programRunnable = new Runnable() { // @Override // public void run() { // logger.log("Programming..."); // // // The logic for this is ported from // // https://github.com/PaulStoffregen/teensy_loader_cli // byte[] buf = new byte[DeviceConstants.BLOCK_SIZE + 64]; // for (int addr = 0; addr < DeviceConstants.FIRMWARE_SIZE; // addr += DeviceConstants.BLOCK_SIZE) { // if (!image.shouldWrite(addr, DeviceConstants.BLOCK_SIZE) && addr != 0) // continue; // don't need to flash this block // // buf[0] = (byte) (addr & 255); // buf[1] = (byte) ((addr >>> 8) & 255); // buf[2] = (byte) ((addr >>> 16) & 255); // Arrays.fill(buf, 3, 64, (byte) 0); // image.getData(buf, 64, addr, DeviceConstants.BLOCK_SIZE); // // conn.write(buf, (addr == 0) ? 3000 : 250); // } // // logger.log("Programming complete. Rebooting."); // // // reboot the device // buf[0] = (byte) 0xFF; // buf[1] = (byte) 0xFF; // buf[2] = (byte) 0xFF; // Arrays.fill(buf, 3, DeviceConstants.BLOCK_SIZE + 64, (byte) 0); // conn.write(buf, 250); // } // }; // } // // Path: android/WALT/app/src/main/java/org/chromium/latency/walt/Utils.java // static boolean getBooleanPreference(Context context, @StringRes int keyId, boolean defaultValue) { // SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); // return preferences.getBoolean(context.getString(keyId), defaultValue); // }
import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.StrictMode; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v4.content.Loader; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import org.chromium.latency.walt.programmer.Programmer; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.Locale; import static org.chromium.latency.walt.Utils.getBooleanPreference;
logger.log("Error syncing clocks: " + e.getMessage()); } } public void onClickCheckDrift(View view) { waltDevice.checkDrift(); } public void onClickProgram(View view) { if (waltDevice.isConnected()) { // show dialog telling user to first press white button final AlertDialog dialog = new AlertDialog.Builder(this) .setTitle("Press white button") .setMessage("Please press the white button on the WALT device.") .setCancelable(false) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) {} }).show(); waltDevice.setConnectionStateListener(new WaltConnection.ConnectionStateListener() { @Override public void onConnect() {} @Override public void onDisconnect() { dialog.cancel(); handler.postDelayed(new Runnable() { @Override public void run() {
// Path: android/WALT/app/src/main/java/org/chromium/latency/walt/programmer/Programmer.java // public class Programmer { // private static final String TAG = "Programmer"; // private SimpleLogger logger; // // private FirmwareImage image; // private BootloaderConnection conn; // // private Context context; // private Handler handler = new Handler(); // // public Programmer(Context context) { // this.context = context; // } // // public void program() { // logger = SimpleLogger.getInstance(context); // InputStream in = context.getResources().openRawResource(R.raw.walt); // image = new FirmwareImage(); // try { // image.parseHex(in); // } catch (ParseException e) { // Log.e(TAG, "Parsing input file: ", e); // } // // conn = BootloaderConnection.getInstance(context); // // TODO: automatically reboot into the bootloader // logger.log("\nRemember to press the button on the Teensy first\n"); // conn.setConnectionStateListener(new WaltConnection.ConnectionStateListener() { // @Override // public void onConnect() { // handler.post(programRunnable); // } // // @Override // public void onDisconnect() {} // }); // if (!conn.isConnected()) { // conn.connect(); // } // } // // private Runnable programRunnable = new Runnable() { // @Override // public void run() { // logger.log("Programming..."); // // // The logic for this is ported from // // https://github.com/PaulStoffregen/teensy_loader_cli // byte[] buf = new byte[DeviceConstants.BLOCK_SIZE + 64]; // for (int addr = 0; addr < DeviceConstants.FIRMWARE_SIZE; // addr += DeviceConstants.BLOCK_SIZE) { // if (!image.shouldWrite(addr, DeviceConstants.BLOCK_SIZE) && addr != 0) // continue; // don't need to flash this block // // buf[0] = (byte) (addr & 255); // buf[1] = (byte) ((addr >>> 8) & 255); // buf[2] = (byte) ((addr >>> 16) & 255); // Arrays.fill(buf, 3, 64, (byte) 0); // image.getData(buf, 64, addr, DeviceConstants.BLOCK_SIZE); // // conn.write(buf, (addr == 0) ? 3000 : 250); // } // // logger.log("Programming complete. Rebooting."); // // // reboot the device // buf[0] = (byte) 0xFF; // buf[1] = (byte) 0xFF; // buf[2] = (byte) 0xFF; // Arrays.fill(buf, 3, DeviceConstants.BLOCK_SIZE + 64, (byte) 0); // conn.write(buf, 250); // } // }; // } // // Path: android/WALT/app/src/main/java/org/chromium/latency/walt/Utils.java // static boolean getBooleanPreference(Context context, @StringRes int keyId, boolean defaultValue) { // SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); // return preferences.getBoolean(context.getString(keyId), defaultValue); // } // Path: android/WALT/app/src/main/java/org/chromium/latency/walt/MainActivity.java import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.StrictMode; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v4.content.Loader; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import org.chromium.latency.walt.programmer.Programmer; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.Locale; import static org.chromium.latency.walt.Utils.getBooleanPreference; logger.log("Error syncing clocks: " + e.getMessage()); } } public void onClickCheckDrift(View view) { waltDevice.checkDrift(); } public void onClickProgram(View view) { if (waltDevice.isConnected()) { // show dialog telling user to first press white button final AlertDialog dialog = new AlertDialog.Builder(this) .setTitle("Press white button") .setMessage("Please press the white button on the WALT device.") .setCancelable(false) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) {} }).show(); waltDevice.setConnectionStateListener(new WaltConnection.ConnectionStateListener() { @Override public void onConnect() {} @Override public void onDisconnect() { dialog.cancel(); handler.postDelayed(new Runnable() { @Override public void run() {
new Programmer(MainActivity.this).program();
google/walt
android/WALT/app/src/main/java/org/chromium/latency/walt/MainActivity.java
// Path: android/WALT/app/src/main/java/org/chromium/latency/walt/programmer/Programmer.java // public class Programmer { // private static final String TAG = "Programmer"; // private SimpleLogger logger; // // private FirmwareImage image; // private BootloaderConnection conn; // // private Context context; // private Handler handler = new Handler(); // // public Programmer(Context context) { // this.context = context; // } // // public void program() { // logger = SimpleLogger.getInstance(context); // InputStream in = context.getResources().openRawResource(R.raw.walt); // image = new FirmwareImage(); // try { // image.parseHex(in); // } catch (ParseException e) { // Log.e(TAG, "Parsing input file: ", e); // } // // conn = BootloaderConnection.getInstance(context); // // TODO: automatically reboot into the bootloader // logger.log("\nRemember to press the button on the Teensy first\n"); // conn.setConnectionStateListener(new WaltConnection.ConnectionStateListener() { // @Override // public void onConnect() { // handler.post(programRunnable); // } // // @Override // public void onDisconnect() {} // }); // if (!conn.isConnected()) { // conn.connect(); // } // } // // private Runnable programRunnable = new Runnable() { // @Override // public void run() { // logger.log("Programming..."); // // // The logic for this is ported from // // https://github.com/PaulStoffregen/teensy_loader_cli // byte[] buf = new byte[DeviceConstants.BLOCK_SIZE + 64]; // for (int addr = 0; addr < DeviceConstants.FIRMWARE_SIZE; // addr += DeviceConstants.BLOCK_SIZE) { // if (!image.shouldWrite(addr, DeviceConstants.BLOCK_SIZE) && addr != 0) // continue; // don't need to flash this block // // buf[0] = (byte) (addr & 255); // buf[1] = (byte) ((addr >>> 8) & 255); // buf[2] = (byte) ((addr >>> 16) & 255); // Arrays.fill(buf, 3, 64, (byte) 0); // image.getData(buf, 64, addr, DeviceConstants.BLOCK_SIZE); // // conn.write(buf, (addr == 0) ? 3000 : 250); // } // // logger.log("Programming complete. Rebooting."); // // // reboot the device // buf[0] = (byte) 0xFF; // buf[1] = (byte) 0xFF; // buf[2] = (byte) 0xFF; // Arrays.fill(buf, 3, DeviceConstants.BLOCK_SIZE + 64, (byte) 0); // conn.write(buf, 250); // } // }; // } // // Path: android/WALT/app/src/main/java/org/chromium/latency/walt/Utils.java // static boolean getBooleanPreference(Context context, @StringRes int keyId, boolean defaultValue) { // SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); // return preferences.getBoolean(context.getString(keyId), defaultValue); // }
import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.StrictMode; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v4.content.Loader; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import org.chromium.latency.walt.programmer.Programmer; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.Locale; import static org.chromium.latency.walt.Utils.getBooleanPreference;
LogUploader uploader = new LogUploader(MainActivity.this, urlString); final String finalUrlString = urlString; uploader.registerListener(1, new Loader.OnLoadCompleteListener<Integer>() { @Override public void onLoadComplete(Loader<Integer> loader, Integer data) { dialog.cancel(); if (data == -1) { Toast.makeText(MainActivity.this, "Failed to upload log", Toast.LENGTH_SHORT).show(); return; } else if (data / 100 == 2) { Toast.makeText(MainActivity.this, "Log successfully uploaded", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Failed to upload log. Server returned status code " + data, Toast.LENGTH_SHORT).show(); } SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(MainActivity.this); preferences.edit().putString( getString(R.string.preference_log_url), finalUrlString).apply(); } }); uploader.startUpload(); } }); } private void requestSystraceWritePermission() {
// Path: android/WALT/app/src/main/java/org/chromium/latency/walt/programmer/Programmer.java // public class Programmer { // private static final String TAG = "Programmer"; // private SimpleLogger logger; // // private FirmwareImage image; // private BootloaderConnection conn; // // private Context context; // private Handler handler = new Handler(); // // public Programmer(Context context) { // this.context = context; // } // // public void program() { // logger = SimpleLogger.getInstance(context); // InputStream in = context.getResources().openRawResource(R.raw.walt); // image = new FirmwareImage(); // try { // image.parseHex(in); // } catch (ParseException e) { // Log.e(TAG, "Parsing input file: ", e); // } // // conn = BootloaderConnection.getInstance(context); // // TODO: automatically reboot into the bootloader // logger.log("\nRemember to press the button on the Teensy first\n"); // conn.setConnectionStateListener(new WaltConnection.ConnectionStateListener() { // @Override // public void onConnect() { // handler.post(programRunnable); // } // // @Override // public void onDisconnect() {} // }); // if (!conn.isConnected()) { // conn.connect(); // } // } // // private Runnable programRunnable = new Runnable() { // @Override // public void run() { // logger.log("Programming..."); // // // The logic for this is ported from // // https://github.com/PaulStoffregen/teensy_loader_cli // byte[] buf = new byte[DeviceConstants.BLOCK_SIZE + 64]; // for (int addr = 0; addr < DeviceConstants.FIRMWARE_SIZE; // addr += DeviceConstants.BLOCK_SIZE) { // if (!image.shouldWrite(addr, DeviceConstants.BLOCK_SIZE) && addr != 0) // continue; // don't need to flash this block // // buf[0] = (byte) (addr & 255); // buf[1] = (byte) ((addr >>> 8) & 255); // buf[2] = (byte) ((addr >>> 16) & 255); // Arrays.fill(buf, 3, 64, (byte) 0); // image.getData(buf, 64, addr, DeviceConstants.BLOCK_SIZE); // // conn.write(buf, (addr == 0) ? 3000 : 250); // } // // logger.log("Programming complete. Rebooting."); // // // reboot the device // buf[0] = (byte) 0xFF; // buf[1] = (byte) 0xFF; // buf[2] = (byte) 0xFF; // Arrays.fill(buf, 3, DeviceConstants.BLOCK_SIZE + 64, (byte) 0); // conn.write(buf, 250); // } // }; // } // // Path: android/WALT/app/src/main/java/org/chromium/latency/walt/Utils.java // static boolean getBooleanPreference(Context context, @StringRes int keyId, boolean defaultValue) { // SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); // return preferences.getBoolean(context.getString(keyId), defaultValue); // } // Path: android/WALT/app/src/main/java/org/chromium/latency/walt/MainActivity.java import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbManager; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.StrictMode; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v4.content.Loader; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import org.chromium.latency.walt.programmer.Programmer; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.Locale; import static org.chromium.latency.walt.Utils.getBooleanPreference; LogUploader uploader = new LogUploader(MainActivity.this, urlString); final String finalUrlString = urlString; uploader.registerListener(1, new Loader.OnLoadCompleteListener<Integer>() { @Override public void onLoadComplete(Loader<Integer> loader, Integer data) { dialog.cancel(); if (data == -1) { Toast.makeText(MainActivity.this, "Failed to upload log", Toast.LENGTH_SHORT).show(); return; } else if (data / 100 == 2) { Toast.makeText(MainActivity.this, "Log successfully uploaded", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Failed to upload log. Server returned status code " + data, Toast.LENGTH_SHORT).show(); } SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(MainActivity.this); preferences.edit().putString( getString(R.string.preference_log_url), finalUrlString).apply(); } }); uploader.startUpload(); } }); } private void requestSystraceWritePermission() {
if (getBooleanPreference(this, R.string.preference_systrace, true)) {
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/persistence/ProductionSaveable.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ProductionMeta.java // public class ProductionMeta { // // private String jobName; // private Date createDate; // private String productionPath; // private String productionPathOfJob; // private int serviceGroup; // private int buildNumber; // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public int getBuildNumber() { // return buildNumber; // } // // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public int getServiceGroup() { // return serviceGroup; // } // // public void setServiceGroup(int serviceGroup) { // this.serviceGroup = serviceGroup; // } // // public String getProductionPath() { // return productionPath; // } // // public void setProductionPath(String productionPath) { // this.productionPath = productionPath; // } // // public String getProductionPathOfJob() { // return productionPathOfJob; // } // // public void setProductionPathOfJob(String productionPathOfJob) { // this.productionPathOfJob = productionPathOfJob; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/util/ModelSoting.java // public class ModelSoting { // public static void serviceSortByWeight(List<ServiceMeta> serviceMetaList){ // // Comparator<ServiceMeta> comparator = new Comparator<ServiceMeta>() { // public int compare(ServiceMeta o1, ServiceMeta o2) { // return (o1.getWeight() > o2.getWeight())? 1 : -1 ; // } // // }; // Collections.sort(serviceMetaList, comparator); // } // // public static void productionSortDate(List<ProductionMeta> productionList){ // Comparator<ProductionMeta> comparator = new Comparator<ProductionMeta>() { // public int compare(ProductionMeta o1, ProductionMeta o2) { // return (o1.getCreateDate().getTime() < o2.getCreateDate().getTime())? 1 : -1 ; // } // }; // // Collections.sort(productionList, comparator); // // } // // // public static void deployRequestSortDate(List<DeployRequest> deployRequestList){ // Comparator<DeployRequest> comparator = new Comparator<DeployRequest>() { // public int compare(DeployRequest o1, DeployRequest o2) { // return (o1.getDate().getTime() < o2.getDate().getTime())? 1 : -1 ; // } // }; // Collections.sort(deployRequestList, comparator); // } // // public static void deployLogSortDate(List<DeployLog> deployLogList){ // Comparator<DeployLog> comparator = new Comparator<DeployLog>() { // public int compare(DeployLog o1, DeployLog o2) { // return (o1.getDate().getTime() < o2.getDate().getTime())? 1 : -1 ; // } // }; // Collections.sort(deployLogList, comparator); // } // // public static void deployReportSortId(List<DeployReport> deployReportList){ // Comparator<DeployReport> comparator = new Comparator<DeployReport>() { // public int compare(DeployReport o1, DeployReport o2) { // return o2.getDeployId().compareTo(o1.getDeployId()); // } // }; // Collections.sort(deployReportList, comparator); // } // }
import java.io.File; import java.io.IOException; import java.util.List; import com.agun.flyJenkins.model.ProductionMeta; import com.agun.flyJenkins.model.util.ModelSoting; import jenkins.model.Jenkins; import hudson.BulkChange; import hudson.XmlFile; import hudson.model.Saveable; import hudson.model.listeners.SaveableListener;
package com.agun.flyJenkins.persistence; public class ProductionSaveable implements Saveable{ List<ProductionMeta> productionMetaList = null; public void save() throws IOException { if(productionMetaList != null){
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ProductionMeta.java // public class ProductionMeta { // // private String jobName; // private Date createDate; // private String productionPath; // private String productionPathOfJob; // private int serviceGroup; // private int buildNumber; // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public int getBuildNumber() { // return buildNumber; // } // // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public int getServiceGroup() { // return serviceGroup; // } // // public void setServiceGroup(int serviceGroup) { // this.serviceGroup = serviceGroup; // } // // public String getProductionPath() { // return productionPath; // } // // public void setProductionPath(String productionPath) { // this.productionPath = productionPath; // } // // public String getProductionPathOfJob() { // return productionPathOfJob; // } // // public void setProductionPathOfJob(String productionPathOfJob) { // this.productionPathOfJob = productionPathOfJob; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/util/ModelSoting.java // public class ModelSoting { // public static void serviceSortByWeight(List<ServiceMeta> serviceMetaList){ // // Comparator<ServiceMeta> comparator = new Comparator<ServiceMeta>() { // public int compare(ServiceMeta o1, ServiceMeta o2) { // return (o1.getWeight() > o2.getWeight())? 1 : -1 ; // } // // }; // Collections.sort(serviceMetaList, comparator); // } // // public static void productionSortDate(List<ProductionMeta> productionList){ // Comparator<ProductionMeta> comparator = new Comparator<ProductionMeta>() { // public int compare(ProductionMeta o1, ProductionMeta o2) { // return (o1.getCreateDate().getTime() < o2.getCreateDate().getTime())? 1 : -1 ; // } // }; // // Collections.sort(productionList, comparator); // // } // // // public static void deployRequestSortDate(List<DeployRequest> deployRequestList){ // Comparator<DeployRequest> comparator = new Comparator<DeployRequest>() { // public int compare(DeployRequest o1, DeployRequest o2) { // return (o1.getDate().getTime() < o2.getDate().getTime())? 1 : -1 ; // } // }; // Collections.sort(deployRequestList, comparator); // } // // public static void deployLogSortDate(List<DeployLog> deployLogList){ // Comparator<DeployLog> comparator = new Comparator<DeployLog>() { // public int compare(DeployLog o1, DeployLog o2) { // return (o1.getDate().getTime() < o2.getDate().getTime())? 1 : -1 ; // } // }; // Collections.sort(deployLogList, comparator); // } // // public static void deployReportSortId(List<DeployReport> deployReportList){ // Comparator<DeployReport> comparator = new Comparator<DeployReport>() { // public int compare(DeployReport o1, DeployReport o2) { // return o2.getDeployId().compareTo(o1.getDeployId()); // } // }; // Collections.sort(deployReportList, comparator); // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/ProductionSaveable.java import java.io.File; import java.io.IOException; import java.util.List; import com.agun.flyJenkins.model.ProductionMeta; import com.agun.flyJenkins.model.util.ModelSoting; import jenkins.model.Jenkins; import hudson.BulkChange; import hudson.XmlFile; import hudson.model.Saveable; import hudson.model.listeners.SaveableListener; package com.agun.flyJenkins.persistence; public class ProductionSaveable implements Saveable{ List<ProductionMeta> productionMetaList = null; public void save() throws IOException { if(productionMetaList != null){
ModelSoting.productionSortDate(productionMetaList);
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/persistence/DeployReportSaveable.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/DeployReport.java // public class DeployReport { // // private String deployId; // private int deploySize = 0; // private int successCount =0; // private int failCount = 0; // // public String getDeployId() { // return deployId; // } // public void setDeployId(String deployId) { // this.deployId = deployId; // } // public int getDeploySize() { // return deploySize; // } // public void setDeploySize(int deploySize) { // this.deploySize = deploySize; // } // public int getSuccessCount() { // return successCount; // } // public void setSuccessCount(int successCount) { // this.successCount = successCount; // } // public int getFailCount() { // return failCount; // } // public void setFailCount(int failCount) { // this.failCount = failCount; // } // // public void plusSuccessCount(){ // this.successCount++; // } // // public void plusFailCount(){ // this.failCount++; // } // // public boolean isFinished(){ // if(deploySize == 0) // return true; // if(deploySize == (failCount + successCount)) // return true; // // return false; // } // // public int getNextOrder(){ // if(isFinished()){ // return 0; // } // // if(deploySize > (failCount + successCount)) // return failCount + successCount +1; // // return 0; // } // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/util/ModelSoting.java // public class ModelSoting { // public static void serviceSortByWeight(List<ServiceMeta> serviceMetaList){ // // Comparator<ServiceMeta> comparator = new Comparator<ServiceMeta>() { // public int compare(ServiceMeta o1, ServiceMeta o2) { // return (o1.getWeight() > o2.getWeight())? 1 : -1 ; // } // // }; // Collections.sort(serviceMetaList, comparator); // } // // public static void productionSortDate(List<ProductionMeta> productionList){ // Comparator<ProductionMeta> comparator = new Comparator<ProductionMeta>() { // public int compare(ProductionMeta o1, ProductionMeta o2) { // return (o1.getCreateDate().getTime() < o2.getCreateDate().getTime())? 1 : -1 ; // } // }; // // Collections.sort(productionList, comparator); // // } // // // public static void deployRequestSortDate(List<DeployRequest> deployRequestList){ // Comparator<DeployRequest> comparator = new Comparator<DeployRequest>() { // public int compare(DeployRequest o1, DeployRequest o2) { // return (o1.getDate().getTime() < o2.getDate().getTime())? 1 : -1 ; // } // }; // Collections.sort(deployRequestList, comparator); // } // // public static void deployLogSortDate(List<DeployLog> deployLogList){ // Comparator<DeployLog> comparator = new Comparator<DeployLog>() { // public int compare(DeployLog o1, DeployLog o2) { // return (o1.getDate().getTime() < o2.getDate().getTime())? 1 : -1 ; // } // }; // Collections.sort(deployLogList, comparator); // } // // public static void deployReportSortId(List<DeployReport> deployReportList){ // Comparator<DeployReport> comparator = new Comparator<DeployReport>() { // public int compare(DeployReport o1, DeployReport o2) { // return o2.getDeployId().compareTo(o1.getDeployId()); // } // }; // Collections.sort(deployReportList, comparator); // } // }
import java.io.File; import java.io.IOException; import java.util.List; import com.agun.flyJenkins.model.DeployReport; import com.agun.flyJenkins.model.util.ModelSoting; import jenkins.model.Jenkins; import hudson.BulkChange; import hudson.XmlFile; import hudson.model.Saveable; import hudson.model.listeners.SaveableListener;
package com.agun.flyJenkins.persistence; public class DeployReportSaveable implements Saveable { List<DeployReport> deployReportList; public void save() throws IOException { if(deployReportList != null)
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/DeployReport.java // public class DeployReport { // // private String deployId; // private int deploySize = 0; // private int successCount =0; // private int failCount = 0; // // public String getDeployId() { // return deployId; // } // public void setDeployId(String deployId) { // this.deployId = deployId; // } // public int getDeploySize() { // return deploySize; // } // public void setDeploySize(int deploySize) { // this.deploySize = deploySize; // } // public int getSuccessCount() { // return successCount; // } // public void setSuccessCount(int successCount) { // this.successCount = successCount; // } // public int getFailCount() { // return failCount; // } // public void setFailCount(int failCount) { // this.failCount = failCount; // } // // public void plusSuccessCount(){ // this.successCount++; // } // // public void plusFailCount(){ // this.failCount++; // } // // public boolean isFinished(){ // if(deploySize == 0) // return true; // if(deploySize == (failCount + successCount)) // return true; // // return false; // } // // public int getNextOrder(){ // if(isFinished()){ // return 0; // } // // if(deploySize > (failCount + successCount)) // return failCount + successCount +1; // // return 0; // } // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/util/ModelSoting.java // public class ModelSoting { // public static void serviceSortByWeight(List<ServiceMeta> serviceMetaList){ // // Comparator<ServiceMeta> comparator = new Comparator<ServiceMeta>() { // public int compare(ServiceMeta o1, ServiceMeta o2) { // return (o1.getWeight() > o2.getWeight())? 1 : -1 ; // } // // }; // Collections.sort(serviceMetaList, comparator); // } // // public static void productionSortDate(List<ProductionMeta> productionList){ // Comparator<ProductionMeta> comparator = new Comparator<ProductionMeta>() { // public int compare(ProductionMeta o1, ProductionMeta o2) { // return (o1.getCreateDate().getTime() < o2.getCreateDate().getTime())? 1 : -1 ; // } // }; // // Collections.sort(productionList, comparator); // // } // // // public static void deployRequestSortDate(List<DeployRequest> deployRequestList){ // Comparator<DeployRequest> comparator = new Comparator<DeployRequest>() { // public int compare(DeployRequest o1, DeployRequest o2) { // return (o1.getDate().getTime() < o2.getDate().getTime())? 1 : -1 ; // } // }; // Collections.sort(deployRequestList, comparator); // } // // public static void deployLogSortDate(List<DeployLog> deployLogList){ // Comparator<DeployLog> comparator = new Comparator<DeployLog>() { // public int compare(DeployLog o1, DeployLog o2) { // return (o1.getDate().getTime() < o2.getDate().getTime())? 1 : -1 ; // } // }; // Collections.sort(deployLogList, comparator); // } // // public static void deployReportSortId(List<DeployReport> deployReportList){ // Comparator<DeployReport> comparator = new Comparator<DeployReport>() { // public int compare(DeployReport o1, DeployReport o2) { // return o2.getDeployId().compareTo(o1.getDeployId()); // } // }; // Collections.sort(deployReportList, comparator); // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/DeployReportSaveable.java import java.io.File; import java.io.IOException; import java.util.List; import com.agun.flyJenkins.model.DeployReport; import com.agun.flyJenkins.model.util.ModelSoting; import jenkins.model.Jenkins; import hudson.BulkChange; import hudson.XmlFile; import hudson.model.Saveable; import hudson.model.listeners.SaveableListener; package com.agun.flyJenkins.persistence; public class DeployReportSaveable implements Saveable { List<DeployReport> deployReportList; public void save() throws IOException { if(deployReportList != null)
ModelSoting.deployReportSortId(deployReportList);
agune/flyJenkins
flyAgent/src/main/java/com/agun/agent/adapter/AdapterFactory.java
// Path: flyAgent/src/main/java/com/agun/agent/model/AgentMeta.java // public class AgentMeta { // // private int id; // private int type; // private int pid; // private int serviceId; // // private String command; // private String testUrl; // // private String destination; // // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getDestination() { // return destination; // } // public void setDestination(String destination) { // this.destination = destination; // } // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public int getPid() { // return pid; // } // public void setPid(int pid) { // this.pid = pid; // } // public String getCommand() { // return command; // } // public void setCommand(String command) { // this.command = command; // } // public int getServiceId() { // return serviceId; // } // public void setServiceId(int serviceId) { // this.serviceId = serviceId; // } // public String getTestUrl() { // return testUrl; // } // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // } // // Path: flyAgent/src/main/java/com/agun/jenkins/FilePathHelper.java // public class FilePathHelper{ // // CLIHelper cliHelper; // // public FilePathHelper(CLIHelper cliHelper){ // // this.cliHelper = cliHelper; // } // // public void copyTo(String src, String target){ // FilePath filePath = new FilePath(new File(target)); // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, src); // // try { // if(fileRemotePath.isDirectory()) // fileRemotePath.copyRecursiveTo(filePath); // else // fileRemotePath.copyTo(filePath); // // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // } // // // // public void sendCopyTo(String src, String target){ // FilePath filePath = new FilePath(new File(target)); // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, src); // // try { // if(filePath.isDirectory()) // filePath.copyRecursiveTo(fileRemotePath); // else // filePath.copyTo(fileRemotePath); // // } catch (IOException e) { // e.printStackTrace(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // public void sendCopyTo(FilePath srcFilePath, String target){ // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, target); // try { // if(srcFilePath.isDirectory()) // srcFilePath.copyRecursiveTo(fileRemotePath); // else // srcFilePath.copyTo(fileRemotePath); // } catch (IOException e) { // e.printStackTrace(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // public FilePath unzip(String zipFileSrc, String target){ // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, zipFileSrc); // FilePath targetFilePath = new FilePath(new File(target)); // try { // fileRemotePath.unzip(targetFilePath); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // return targetFilePath; // } // }
import com.agun.agent.model.AgentMeta; import com.agun.jenkins.FilePathHelper;
package com.agun.agent.adapter; public class AdapterFactory { private AdapterFactory(){} private static TomcatService tomcatService = new TomcatService(); private static GeneralService generalService = new GeneralService(); private static EtcService etcService = new EtcService();
// Path: flyAgent/src/main/java/com/agun/agent/model/AgentMeta.java // public class AgentMeta { // // private int id; // private int type; // private int pid; // private int serviceId; // // private String command; // private String testUrl; // // private String destination; // // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getDestination() { // return destination; // } // public void setDestination(String destination) { // this.destination = destination; // } // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public int getPid() { // return pid; // } // public void setPid(int pid) { // this.pid = pid; // } // public String getCommand() { // return command; // } // public void setCommand(String command) { // this.command = command; // } // public int getServiceId() { // return serviceId; // } // public void setServiceId(int serviceId) { // this.serviceId = serviceId; // } // public String getTestUrl() { // return testUrl; // } // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // } // // Path: flyAgent/src/main/java/com/agun/jenkins/FilePathHelper.java // public class FilePathHelper{ // // CLIHelper cliHelper; // // public FilePathHelper(CLIHelper cliHelper){ // // this.cliHelper = cliHelper; // } // // public void copyTo(String src, String target){ // FilePath filePath = new FilePath(new File(target)); // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, src); // // try { // if(fileRemotePath.isDirectory()) // fileRemotePath.copyRecursiveTo(filePath); // else // fileRemotePath.copyTo(filePath); // // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // } // // // // public void sendCopyTo(String src, String target){ // FilePath filePath = new FilePath(new File(target)); // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, src); // // try { // if(filePath.isDirectory()) // filePath.copyRecursiveTo(fileRemotePath); // else // filePath.copyTo(fileRemotePath); // // } catch (IOException e) { // e.printStackTrace(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // public void sendCopyTo(FilePath srcFilePath, String target){ // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, target); // try { // if(srcFilePath.isDirectory()) // srcFilePath.copyRecursiveTo(fileRemotePath); // else // srcFilePath.copyTo(fileRemotePath); // } catch (IOException e) { // e.printStackTrace(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // public FilePath unzip(String zipFileSrc, String target){ // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, zipFileSrc); // FilePath targetFilePath = new FilePath(new File(target)); // try { // fileRemotePath.unzip(targetFilePath); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // return targetFilePath; // } // } // Path: flyAgent/src/main/java/com/agun/agent/adapter/AdapterFactory.java import com.agun.agent.model.AgentMeta; import com.agun.jenkins.FilePathHelper; package com.agun.agent.adapter; public class AdapterFactory { private AdapterFactory(){} private static TomcatService tomcatService = new TomcatService(); private static GeneralService generalService = new GeneralService(); private static EtcService etcService = new EtcService();
public static ServiceType getServiceType(AgentMeta agentMeta, FilePathHelper filePathHelper){
agune/flyJenkins
flyAgent/src/main/java/com/agun/agent/adapter/AdapterFactory.java
// Path: flyAgent/src/main/java/com/agun/agent/model/AgentMeta.java // public class AgentMeta { // // private int id; // private int type; // private int pid; // private int serviceId; // // private String command; // private String testUrl; // // private String destination; // // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getDestination() { // return destination; // } // public void setDestination(String destination) { // this.destination = destination; // } // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public int getPid() { // return pid; // } // public void setPid(int pid) { // this.pid = pid; // } // public String getCommand() { // return command; // } // public void setCommand(String command) { // this.command = command; // } // public int getServiceId() { // return serviceId; // } // public void setServiceId(int serviceId) { // this.serviceId = serviceId; // } // public String getTestUrl() { // return testUrl; // } // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // } // // Path: flyAgent/src/main/java/com/agun/jenkins/FilePathHelper.java // public class FilePathHelper{ // // CLIHelper cliHelper; // // public FilePathHelper(CLIHelper cliHelper){ // // this.cliHelper = cliHelper; // } // // public void copyTo(String src, String target){ // FilePath filePath = new FilePath(new File(target)); // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, src); // // try { // if(fileRemotePath.isDirectory()) // fileRemotePath.copyRecursiveTo(filePath); // else // fileRemotePath.copyTo(filePath); // // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // } // // // // public void sendCopyTo(String src, String target){ // FilePath filePath = new FilePath(new File(target)); // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, src); // // try { // if(filePath.isDirectory()) // filePath.copyRecursiveTo(fileRemotePath); // else // filePath.copyTo(fileRemotePath); // // } catch (IOException e) { // e.printStackTrace(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // public void sendCopyTo(FilePath srcFilePath, String target){ // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, target); // try { // if(srcFilePath.isDirectory()) // srcFilePath.copyRecursiveTo(fileRemotePath); // else // srcFilePath.copyTo(fileRemotePath); // } catch (IOException e) { // e.printStackTrace(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // public FilePath unzip(String zipFileSrc, String target){ // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, zipFileSrc); // FilePath targetFilePath = new FilePath(new File(target)); // try { // fileRemotePath.unzip(targetFilePath); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // return targetFilePath; // } // }
import com.agun.agent.model.AgentMeta; import com.agun.jenkins.FilePathHelper;
package com.agun.agent.adapter; public class AdapterFactory { private AdapterFactory(){} private static TomcatService tomcatService = new TomcatService(); private static GeneralService generalService = new GeneralService(); private static EtcService etcService = new EtcService();
// Path: flyAgent/src/main/java/com/agun/agent/model/AgentMeta.java // public class AgentMeta { // // private int id; // private int type; // private int pid; // private int serviceId; // // private String command; // private String testUrl; // // private String destination; // // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getDestination() { // return destination; // } // public void setDestination(String destination) { // this.destination = destination; // } // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public int getPid() { // return pid; // } // public void setPid(int pid) { // this.pid = pid; // } // public String getCommand() { // return command; // } // public void setCommand(String command) { // this.command = command; // } // public int getServiceId() { // return serviceId; // } // public void setServiceId(int serviceId) { // this.serviceId = serviceId; // } // public String getTestUrl() { // return testUrl; // } // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // } // // Path: flyAgent/src/main/java/com/agun/jenkins/FilePathHelper.java // public class FilePathHelper{ // // CLIHelper cliHelper; // // public FilePathHelper(CLIHelper cliHelper){ // // this.cliHelper = cliHelper; // } // // public void copyTo(String src, String target){ // FilePath filePath = new FilePath(new File(target)); // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, src); // // try { // if(fileRemotePath.isDirectory()) // fileRemotePath.copyRecursiveTo(filePath); // else // fileRemotePath.copyTo(filePath); // // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // } // // // // public void sendCopyTo(String src, String target){ // FilePath filePath = new FilePath(new File(target)); // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, src); // // try { // if(filePath.isDirectory()) // filePath.copyRecursiveTo(fileRemotePath); // else // filePath.copyTo(fileRemotePath); // // } catch (IOException e) { // e.printStackTrace(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // public void sendCopyTo(FilePath srcFilePath, String target){ // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, target); // try { // if(srcFilePath.isDirectory()) // srcFilePath.copyRecursiveTo(fileRemotePath); // else // srcFilePath.copyTo(fileRemotePath); // } catch (IOException e) { // e.printStackTrace(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // public FilePath unzip(String zipFileSrc, String target){ // Channel channel = cliHelper.getChannel(); // FilePath fileRemotePath = new FilePath(channel, zipFileSrc); // FilePath targetFilePath = new FilePath(new File(target)); // try { // fileRemotePath.unzip(targetFilePath); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // return targetFilePath; // } // } // Path: flyAgent/src/main/java/com/agun/agent/adapter/AdapterFactory.java import com.agun.agent.model.AgentMeta; import com.agun.jenkins.FilePathHelper; package com.agun.agent.adapter; public class AdapterFactory { private AdapterFactory(){} private static TomcatService tomcatService = new TomcatService(); private static GeneralService generalService = new GeneralService(); private static EtcService etcService = new EtcService();
public static ServiceType getServiceType(AgentMeta agentMeta, FilePathHelper filePathHelper){
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/deploy/DeployProduction.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ProductionMeta.java // public class ProductionMeta { // // private String jobName; // private Date createDate; // private String productionPath; // private String productionPathOfJob; // private int serviceGroup; // private int buildNumber; // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public int getBuildNumber() { // return buildNumber; // } // // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public int getServiceGroup() { // return serviceGroup; // } // // public void setServiceGroup(int serviceGroup) { // this.serviceGroup = serviceGroup; // } // // public String getProductionPath() { // return productionPath; // } // // public void setProductionPath(String productionPath) { // this.productionPath = productionPath; // } // // public String getProductionPathOfJob() { // return productionPathOfJob; // } // // public void setProductionPathOfJob(String productionPathOfJob) { // this.productionPathOfJob = productionPathOfJob; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/ProductionSaveable.java // public class ProductionSaveable implements Saveable{ // // List<ProductionMeta> productionMetaList = null; // // public void save() throws IOException { // if(productionMetaList != null){ // ModelSoting.productionSortDate(productionMetaList); // } // if(BulkChange.contains(this)) return; // try { // getConfigFile().write(this); // SaveableListener.fireOnChange(this, getConfigFile()); // } catch (IOException e) { // e.printStackTrace(); // } // // } // protected XmlFile getConfigFile() { // // return new XmlFile(new File(Jenkins.getInstance().getRootDir(), this.getClass().getSimpleName()+".xml")); // } // // // /** // * open file and load data // */ // public synchronized void load() { // XmlFile file = getConfigFile(); // if(!file.exists()) // return; // try { // file.unmarshal(this); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<ProductionMeta> getProductionMetaList() { // return productionMetaList; // } // // public void setProductionMetaList(List<ProductionMeta> productionMetaList) { // this.productionMetaList = productionMetaList; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/util/FlyJenkinsEnv.java // public class FlyJenkinsEnv { // // public static String getProductionRoot(){ // return Jenkins.getInstance().getRootDir().getAbsolutePath() + "/flyJenkins/job"; // } // // public static String getLastBuildPath(int serviceId){ // return Jenkins.getInstance().getRootDir().getAbsolutePath() + "/flyJenkins/lastBuild/"+serviceId+"/service.zip"; // } // }
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import jenkins.model.Jenkins; import hudson.FilePath; import hudson.model.AbstractBuild; import com.agun.flyJenkins.model.ProductionMeta; import com.agun.flyJenkins.persistence.ProductionSaveable; import com.agun.flyJenkins.util.FlyJenkinsEnv;
package com.agun.flyJenkins.deploy; /** * this class handle production when build * @author agun * */ public class DeployProduction { public final static String SUCCESS = "SUCCESS"; public final static String FAIL = "FAILURE"; /** * check state of building * @param result * @return */ public static boolean isSuccess(String result){ return (result == null || "SUCCESS".equals(result) == false) ? false : true; } /** * handle production when build * @param jobName * @param production * @param build * @return */ public boolean process(String jobName, String production, int serviceGroup, AbstractBuild<?,?> build){
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ProductionMeta.java // public class ProductionMeta { // // private String jobName; // private Date createDate; // private String productionPath; // private String productionPathOfJob; // private int serviceGroup; // private int buildNumber; // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public int getBuildNumber() { // return buildNumber; // } // // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public int getServiceGroup() { // return serviceGroup; // } // // public void setServiceGroup(int serviceGroup) { // this.serviceGroup = serviceGroup; // } // // public String getProductionPath() { // return productionPath; // } // // public void setProductionPath(String productionPath) { // this.productionPath = productionPath; // } // // public String getProductionPathOfJob() { // return productionPathOfJob; // } // // public void setProductionPathOfJob(String productionPathOfJob) { // this.productionPathOfJob = productionPathOfJob; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/ProductionSaveable.java // public class ProductionSaveable implements Saveable{ // // List<ProductionMeta> productionMetaList = null; // // public void save() throws IOException { // if(productionMetaList != null){ // ModelSoting.productionSortDate(productionMetaList); // } // if(BulkChange.contains(this)) return; // try { // getConfigFile().write(this); // SaveableListener.fireOnChange(this, getConfigFile()); // } catch (IOException e) { // e.printStackTrace(); // } // // } // protected XmlFile getConfigFile() { // // return new XmlFile(new File(Jenkins.getInstance().getRootDir(), this.getClass().getSimpleName()+".xml")); // } // // // /** // * open file and load data // */ // public synchronized void load() { // XmlFile file = getConfigFile(); // if(!file.exists()) // return; // try { // file.unmarshal(this); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<ProductionMeta> getProductionMetaList() { // return productionMetaList; // } // // public void setProductionMetaList(List<ProductionMeta> productionMetaList) { // this.productionMetaList = productionMetaList; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/util/FlyJenkinsEnv.java // public class FlyJenkinsEnv { // // public static String getProductionRoot(){ // return Jenkins.getInstance().getRootDir().getAbsolutePath() + "/flyJenkins/job"; // } // // public static String getLastBuildPath(int serviceId){ // return Jenkins.getInstance().getRootDir().getAbsolutePath() + "/flyJenkins/lastBuild/"+serviceId+"/service.zip"; // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/deploy/DeployProduction.java import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import jenkins.model.Jenkins; import hudson.FilePath; import hudson.model.AbstractBuild; import com.agun.flyJenkins.model.ProductionMeta; import com.agun.flyJenkins.persistence.ProductionSaveable; import com.agun.flyJenkins.util.FlyJenkinsEnv; package com.agun.flyJenkins.deploy; /** * this class handle production when build * @author agun * */ public class DeployProduction { public final static String SUCCESS = "SUCCESS"; public final static String FAIL = "FAILURE"; /** * check state of building * @param result * @return */ public static boolean isSuccess(String result){ return (result == null || "SUCCESS".equals(result) == false) ? false : true; } /** * handle production when build * @param jobName * @param production * @param build * @return */ public boolean process(String jobName, String production, int serviceGroup, AbstractBuild<?,?> build){
ProductionMeta productionMeta = normalizationProductionMeta(jobName, production, serviceGroup, build);
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/deploy/DeployProduction.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ProductionMeta.java // public class ProductionMeta { // // private String jobName; // private Date createDate; // private String productionPath; // private String productionPathOfJob; // private int serviceGroup; // private int buildNumber; // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public int getBuildNumber() { // return buildNumber; // } // // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public int getServiceGroup() { // return serviceGroup; // } // // public void setServiceGroup(int serviceGroup) { // this.serviceGroup = serviceGroup; // } // // public String getProductionPath() { // return productionPath; // } // // public void setProductionPath(String productionPath) { // this.productionPath = productionPath; // } // // public String getProductionPathOfJob() { // return productionPathOfJob; // } // // public void setProductionPathOfJob(String productionPathOfJob) { // this.productionPathOfJob = productionPathOfJob; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/ProductionSaveable.java // public class ProductionSaveable implements Saveable{ // // List<ProductionMeta> productionMetaList = null; // // public void save() throws IOException { // if(productionMetaList != null){ // ModelSoting.productionSortDate(productionMetaList); // } // if(BulkChange.contains(this)) return; // try { // getConfigFile().write(this); // SaveableListener.fireOnChange(this, getConfigFile()); // } catch (IOException e) { // e.printStackTrace(); // } // // } // protected XmlFile getConfigFile() { // // return new XmlFile(new File(Jenkins.getInstance().getRootDir(), this.getClass().getSimpleName()+".xml")); // } // // // /** // * open file and load data // */ // public synchronized void load() { // XmlFile file = getConfigFile(); // if(!file.exists()) // return; // try { // file.unmarshal(this); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<ProductionMeta> getProductionMetaList() { // return productionMetaList; // } // // public void setProductionMetaList(List<ProductionMeta> productionMetaList) { // this.productionMetaList = productionMetaList; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/util/FlyJenkinsEnv.java // public class FlyJenkinsEnv { // // public static String getProductionRoot(){ // return Jenkins.getInstance().getRootDir().getAbsolutePath() + "/flyJenkins/job"; // } // // public static String getLastBuildPath(int serviceId){ // return Jenkins.getInstance().getRootDir().getAbsolutePath() + "/flyJenkins/lastBuild/"+serviceId+"/service.zip"; // } // }
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import jenkins.model.Jenkins; import hudson.FilePath; import hudson.model.AbstractBuild; import com.agun.flyJenkins.model.ProductionMeta; import com.agun.flyJenkins.persistence.ProductionSaveable; import com.agun.flyJenkins.util.FlyJenkinsEnv;
package com.agun.flyJenkins.deploy; /** * this class handle production when build * @author agun * */ public class DeployProduction { public final static String SUCCESS = "SUCCESS"; public final static String FAIL = "FAILURE"; /** * check state of building * @param result * @return */ public static boolean isSuccess(String result){ return (result == null || "SUCCESS".equals(result) == false) ? false : true; } /** * handle production when build * @param jobName * @param production * @param build * @return */ public boolean process(String jobName, String production, int serviceGroup, AbstractBuild<?,?> build){ ProductionMeta productionMeta = normalizationProductionMeta(jobName, production, serviceGroup, build); makeJobDir(productionMeta, build); compressToCopy(productionMeta); saveProductionMeta(productionMeta); return true; } private ProductionMeta normalizationProductionMeta(String jobName, String production, int serviceGroup, AbstractBuild<?,?> build){ ProductionMeta productionMeta = new ProductionMeta(); productionMeta.setJobName(jobName); productionMeta.setCreateDate(new Date()); productionMeta.setBuildNumber(build.getNumber()); productionMeta.setProductionPath(production); productionMeta.setServiceGroup(serviceGroup); String filename = getName(production);
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ProductionMeta.java // public class ProductionMeta { // // private String jobName; // private Date createDate; // private String productionPath; // private String productionPathOfJob; // private int serviceGroup; // private int buildNumber; // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public int getBuildNumber() { // return buildNumber; // } // // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public int getServiceGroup() { // return serviceGroup; // } // // public void setServiceGroup(int serviceGroup) { // this.serviceGroup = serviceGroup; // } // // public String getProductionPath() { // return productionPath; // } // // public void setProductionPath(String productionPath) { // this.productionPath = productionPath; // } // // public String getProductionPathOfJob() { // return productionPathOfJob; // } // // public void setProductionPathOfJob(String productionPathOfJob) { // this.productionPathOfJob = productionPathOfJob; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/ProductionSaveable.java // public class ProductionSaveable implements Saveable{ // // List<ProductionMeta> productionMetaList = null; // // public void save() throws IOException { // if(productionMetaList != null){ // ModelSoting.productionSortDate(productionMetaList); // } // if(BulkChange.contains(this)) return; // try { // getConfigFile().write(this); // SaveableListener.fireOnChange(this, getConfigFile()); // } catch (IOException e) { // e.printStackTrace(); // } // // } // protected XmlFile getConfigFile() { // // return new XmlFile(new File(Jenkins.getInstance().getRootDir(), this.getClass().getSimpleName()+".xml")); // } // // // /** // * open file and load data // */ // public synchronized void load() { // XmlFile file = getConfigFile(); // if(!file.exists()) // return; // try { // file.unmarshal(this); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<ProductionMeta> getProductionMetaList() { // return productionMetaList; // } // // public void setProductionMetaList(List<ProductionMeta> productionMetaList) { // this.productionMetaList = productionMetaList; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/util/FlyJenkinsEnv.java // public class FlyJenkinsEnv { // // public static String getProductionRoot(){ // return Jenkins.getInstance().getRootDir().getAbsolutePath() + "/flyJenkins/job"; // } // // public static String getLastBuildPath(int serviceId){ // return Jenkins.getInstance().getRootDir().getAbsolutePath() + "/flyJenkins/lastBuild/"+serviceId+"/service.zip"; // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/deploy/DeployProduction.java import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import jenkins.model.Jenkins; import hudson.FilePath; import hudson.model.AbstractBuild; import com.agun.flyJenkins.model.ProductionMeta; import com.agun.flyJenkins.persistence.ProductionSaveable; import com.agun.flyJenkins.util.FlyJenkinsEnv; package com.agun.flyJenkins.deploy; /** * this class handle production when build * @author agun * */ public class DeployProduction { public final static String SUCCESS = "SUCCESS"; public final static String FAIL = "FAILURE"; /** * check state of building * @param result * @return */ public static boolean isSuccess(String result){ return (result == null || "SUCCESS".equals(result) == false) ? false : true; } /** * handle production when build * @param jobName * @param production * @param build * @return */ public boolean process(String jobName, String production, int serviceGroup, AbstractBuild<?,?> build){ ProductionMeta productionMeta = normalizationProductionMeta(jobName, production, serviceGroup, build); makeJobDir(productionMeta, build); compressToCopy(productionMeta); saveProductionMeta(productionMeta); return true; } private ProductionMeta normalizationProductionMeta(String jobName, String production, int serviceGroup, AbstractBuild<?,?> build){ ProductionMeta productionMeta = new ProductionMeta(); productionMeta.setJobName(jobName); productionMeta.setCreateDate(new Date()); productionMeta.setBuildNumber(build.getNumber()); productionMeta.setProductionPath(production); productionMeta.setServiceGroup(serviceGroup); String filename = getName(production);
String productionPathOfJob = FlyJenkinsEnv.getProductionRoot() + "/"+ jobName + "/" + build.getNumber() + "/" + filename;
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/deploy/DeployProduction.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ProductionMeta.java // public class ProductionMeta { // // private String jobName; // private Date createDate; // private String productionPath; // private String productionPathOfJob; // private int serviceGroup; // private int buildNumber; // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public int getBuildNumber() { // return buildNumber; // } // // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public int getServiceGroup() { // return serviceGroup; // } // // public void setServiceGroup(int serviceGroup) { // this.serviceGroup = serviceGroup; // } // // public String getProductionPath() { // return productionPath; // } // // public void setProductionPath(String productionPath) { // this.productionPath = productionPath; // } // // public String getProductionPathOfJob() { // return productionPathOfJob; // } // // public void setProductionPathOfJob(String productionPathOfJob) { // this.productionPathOfJob = productionPathOfJob; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/ProductionSaveable.java // public class ProductionSaveable implements Saveable{ // // List<ProductionMeta> productionMetaList = null; // // public void save() throws IOException { // if(productionMetaList != null){ // ModelSoting.productionSortDate(productionMetaList); // } // if(BulkChange.contains(this)) return; // try { // getConfigFile().write(this); // SaveableListener.fireOnChange(this, getConfigFile()); // } catch (IOException e) { // e.printStackTrace(); // } // // } // protected XmlFile getConfigFile() { // // return new XmlFile(new File(Jenkins.getInstance().getRootDir(), this.getClass().getSimpleName()+".xml")); // } // // // /** // * open file and load data // */ // public synchronized void load() { // XmlFile file = getConfigFile(); // if(!file.exists()) // return; // try { // file.unmarshal(this); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<ProductionMeta> getProductionMetaList() { // return productionMetaList; // } // // public void setProductionMetaList(List<ProductionMeta> productionMetaList) { // this.productionMetaList = productionMetaList; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/util/FlyJenkinsEnv.java // public class FlyJenkinsEnv { // // public static String getProductionRoot(){ // return Jenkins.getInstance().getRootDir().getAbsolutePath() + "/flyJenkins/job"; // } // // public static String getLastBuildPath(int serviceId){ // return Jenkins.getInstance().getRootDir().getAbsolutePath() + "/flyJenkins/lastBuild/"+serviceId+"/service.zip"; // } // }
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import jenkins.model.Jenkins; import hudson.FilePath; import hudson.model.AbstractBuild; import com.agun.flyJenkins.model.ProductionMeta; import com.agun.flyJenkins.persistence.ProductionSaveable; import com.agun.flyJenkins.util.FlyJenkinsEnv;
e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } private void compressToCopy(ProductionMeta productionMeta){ String targetPathString = productionMeta.getProductionPath(); String destinationPathString =productionMeta.getProductionPathOfJob(); FilePath targetPath = new FilePath(new File(targetPathString)); FilePath destinationPath = new FilePath(new File(destinationPathString)); try { if(targetPath.exists() == false) return; if(targetPath.isDirectory()) targetPath.copyRecursiveTo(destinationPath); else targetPath.copyTo(destinationPath); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } private void saveProductionMeta(ProductionMeta productionMeta){
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ProductionMeta.java // public class ProductionMeta { // // private String jobName; // private Date createDate; // private String productionPath; // private String productionPathOfJob; // private int serviceGroup; // private int buildNumber; // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public int getBuildNumber() { // return buildNumber; // } // // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public int getServiceGroup() { // return serviceGroup; // } // // public void setServiceGroup(int serviceGroup) { // this.serviceGroup = serviceGroup; // } // // public String getProductionPath() { // return productionPath; // } // // public void setProductionPath(String productionPath) { // this.productionPath = productionPath; // } // // public String getProductionPathOfJob() { // return productionPathOfJob; // } // // public void setProductionPathOfJob(String productionPathOfJob) { // this.productionPathOfJob = productionPathOfJob; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/ProductionSaveable.java // public class ProductionSaveable implements Saveable{ // // List<ProductionMeta> productionMetaList = null; // // public void save() throws IOException { // if(productionMetaList != null){ // ModelSoting.productionSortDate(productionMetaList); // } // if(BulkChange.contains(this)) return; // try { // getConfigFile().write(this); // SaveableListener.fireOnChange(this, getConfigFile()); // } catch (IOException e) { // e.printStackTrace(); // } // // } // protected XmlFile getConfigFile() { // // return new XmlFile(new File(Jenkins.getInstance().getRootDir(), this.getClass().getSimpleName()+".xml")); // } // // // /** // * open file and load data // */ // public synchronized void load() { // XmlFile file = getConfigFile(); // if(!file.exists()) // return; // try { // file.unmarshal(this); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<ProductionMeta> getProductionMetaList() { // return productionMetaList; // } // // public void setProductionMetaList(List<ProductionMeta> productionMetaList) { // this.productionMetaList = productionMetaList; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/util/FlyJenkinsEnv.java // public class FlyJenkinsEnv { // // public static String getProductionRoot(){ // return Jenkins.getInstance().getRootDir().getAbsolutePath() + "/flyJenkins/job"; // } // // public static String getLastBuildPath(int serviceId){ // return Jenkins.getInstance().getRootDir().getAbsolutePath() + "/flyJenkins/lastBuild/"+serviceId+"/service.zip"; // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/deploy/DeployProduction.java import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import jenkins.model.Jenkins; import hudson.FilePath; import hudson.model.AbstractBuild; import com.agun.flyJenkins.model.ProductionMeta; import com.agun.flyJenkins.persistence.ProductionSaveable; import com.agun.flyJenkins.util.FlyJenkinsEnv; e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } private void compressToCopy(ProductionMeta productionMeta){ String targetPathString = productionMeta.getProductionPath(); String destinationPathString =productionMeta.getProductionPathOfJob(); FilePath targetPath = new FilePath(new File(targetPathString)); FilePath destinationPath = new FilePath(new File(destinationPathString)); try { if(targetPath.exists() == false) return; if(targetPath.isDirectory()) targetPath.copyRecursiveTo(destinationPath); else targetPath.copyTo(destinationPath); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } private void saveProductionMeta(ProductionMeta productionMeta){
ProductionSaveable productionSaveable = new ProductionSaveable();
agune/flyJenkins
flyJenkins/src/main/java/org/flyJenkins/component/persistent/hsql/ProductionDriver.java
// Path: flyJenkins/src/main/java/org/flyJenkins/component/persistent/PersistentDriver.java // public interface PersistentDriver { // public void initDevice(); // public void initSchema(); // public Connection getConn(); // public Statement getStatement(); // } // // Path: flyJenkins/src/main/java/org/flyJenkins/component/persistent/QueryDriver.java // public interface QueryDriver { // public void setPersistentDriver(PersistentDriver persistentDriver); // public <T1> void query(T1 t1) throws IllegalArgumentException; // public <T1> void query(List<T1> t1List); // public <T2> List<T2> getPageList(int page , int limit); // public <T3> T3 read(T3 t3); // public <T4> int getTotalPage(T4 t4, int limit); // public <T5> void del(T5 t5); // } // // Path: common/src/main/java/org/flyJenkins/model/Production.java // public class Production { // // private int productionID; // // // job id of building // private int jobID; // // private String jobName; // private int buildNumber; // // private String output; // private Date createDate; // // public int getJobID() { // return jobID; // } // public void setJobID(int jobID) { // this.jobID = jobID; // } // public String getJobName() { // return jobName; // } // public void setJobName(String jobName) { // this.jobName = jobName; // } // public int getBuildNumber() { // return buildNumber; // } // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // public String getOutput() { // return output; // } // public void setOutput(String output) { // this.output = output; // } // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // // // public int getProductionID() { // return productionID; // } // public void setProductionID(int productionID) { // this.productionID = productionID; // } // // }
import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.flyJenkins.component.persistent.PersistentDriver; import org.flyJenkins.component.persistent.QueryDriver; import org.flyJenkins.model.Production;
/** * production query driver class * @author agun */ package org.flyJenkins.component.persistent.hsql; /** * TODO refactoring * @author agun * */ public class ProductionDriver implements QueryDriver { Statement st = null;
// Path: flyJenkins/src/main/java/org/flyJenkins/component/persistent/PersistentDriver.java // public interface PersistentDriver { // public void initDevice(); // public void initSchema(); // public Connection getConn(); // public Statement getStatement(); // } // // Path: flyJenkins/src/main/java/org/flyJenkins/component/persistent/QueryDriver.java // public interface QueryDriver { // public void setPersistentDriver(PersistentDriver persistentDriver); // public <T1> void query(T1 t1) throws IllegalArgumentException; // public <T1> void query(List<T1> t1List); // public <T2> List<T2> getPageList(int page , int limit); // public <T3> T3 read(T3 t3); // public <T4> int getTotalPage(T4 t4, int limit); // public <T5> void del(T5 t5); // } // // Path: common/src/main/java/org/flyJenkins/model/Production.java // public class Production { // // private int productionID; // // // job id of building // private int jobID; // // private String jobName; // private int buildNumber; // // private String output; // private Date createDate; // // public int getJobID() { // return jobID; // } // public void setJobID(int jobID) { // this.jobID = jobID; // } // public String getJobName() { // return jobName; // } // public void setJobName(String jobName) { // this.jobName = jobName; // } // public int getBuildNumber() { // return buildNumber; // } // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // public String getOutput() { // return output; // } // public void setOutput(String output) { // this.output = output; // } // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // // // public int getProductionID() { // return productionID; // } // public void setProductionID(int productionID) { // this.productionID = productionID; // } // // } // Path: flyJenkins/src/main/java/org/flyJenkins/component/persistent/hsql/ProductionDriver.java import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.flyJenkins.component.persistent.PersistentDriver; import org.flyJenkins.component.persistent.QueryDriver; import org.flyJenkins.model.Production; /** * production query driver class * @author agun */ package org.flyJenkins.component.persistent.hsql; /** * TODO refactoring * @author agun * */ public class ProductionDriver implements QueryDriver { Statement st = null;
PersistentDriver persistentDriver = null;
agune/flyJenkins
flyJenkins/src/main/java/org/flyJenkins/component/persistent/hsql/ProductionDriver.java
// Path: flyJenkins/src/main/java/org/flyJenkins/component/persistent/PersistentDriver.java // public interface PersistentDriver { // public void initDevice(); // public void initSchema(); // public Connection getConn(); // public Statement getStatement(); // } // // Path: flyJenkins/src/main/java/org/flyJenkins/component/persistent/QueryDriver.java // public interface QueryDriver { // public void setPersistentDriver(PersistentDriver persistentDriver); // public <T1> void query(T1 t1) throws IllegalArgumentException; // public <T1> void query(List<T1> t1List); // public <T2> List<T2> getPageList(int page , int limit); // public <T3> T3 read(T3 t3); // public <T4> int getTotalPage(T4 t4, int limit); // public <T5> void del(T5 t5); // } // // Path: common/src/main/java/org/flyJenkins/model/Production.java // public class Production { // // private int productionID; // // // job id of building // private int jobID; // // private String jobName; // private int buildNumber; // // private String output; // private Date createDate; // // public int getJobID() { // return jobID; // } // public void setJobID(int jobID) { // this.jobID = jobID; // } // public String getJobName() { // return jobName; // } // public void setJobName(String jobName) { // this.jobName = jobName; // } // public int getBuildNumber() { // return buildNumber; // } // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // public String getOutput() { // return output; // } // public void setOutput(String output) { // this.output = output; // } // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // // // public int getProductionID() { // return productionID; // } // public void setProductionID(int productionID) { // this.productionID = productionID; // } // // }
import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.flyJenkins.component.persistent.PersistentDriver; import org.flyJenkins.component.persistent.QueryDriver; import org.flyJenkins.model.Production;
/** * production query driver class * @author agun */ package org.flyJenkins.component.persistent.hsql; /** * TODO refactoring * @author agun * */ public class ProductionDriver implements QueryDriver { Statement st = null; PersistentDriver persistentDriver = null; public <T1> void query(T1 t1) throws IllegalArgumentException { Statement st = persistentDriver.getStatement();
// Path: flyJenkins/src/main/java/org/flyJenkins/component/persistent/PersistentDriver.java // public interface PersistentDriver { // public void initDevice(); // public void initSchema(); // public Connection getConn(); // public Statement getStatement(); // } // // Path: flyJenkins/src/main/java/org/flyJenkins/component/persistent/QueryDriver.java // public interface QueryDriver { // public void setPersistentDriver(PersistentDriver persistentDriver); // public <T1> void query(T1 t1) throws IllegalArgumentException; // public <T1> void query(List<T1> t1List); // public <T2> List<T2> getPageList(int page , int limit); // public <T3> T3 read(T3 t3); // public <T4> int getTotalPage(T4 t4, int limit); // public <T5> void del(T5 t5); // } // // Path: common/src/main/java/org/flyJenkins/model/Production.java // public class Production { // // private int productionID; // // // job id of building // private int jobID; // // private String jobName; // private int buildNumber; // // private String output; // private Date createDate; // // public int getJobID() { // return jobID; // } // public void setJobID(int jobID) { // this.jobID = jobID; // } // public String getJobName() { // return jobName; // } // public void setJobName(String jobName) { // this.jobName = jobName; // } // public int getBuildNumber() { // return buildNumber; // } // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // public String getOutput() { // return output; // } // public void setOutput(String output) { // this.output = output; // } // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // // // public int getProductionID() { // return productionID; // } // public void setProductionID(int productionID) { // this.productionID = productionID; // } // // } // Path: flyJenkins/src/main/java/org/flyJenkins/component/persistent/hsql/ProductionDriver.java import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.flyJenkins.component.persistent.PersistentDriver; import org.flyJenkins.component.persistent.QueryDriver; import org.flyJenkins.model.Production; /** * production query driver class * @author agun */ package org.flyJenkins.component.persistent.hsql; /** * TODO refactoring * @author agun * */ public class ProductionDriver implements QueryDriver { Statement st = null; PersistentDriver persistentDriver = null; public <T1> void query(T1 t1) throws IllegalArgumentException { Statement st = persistentDriver.getStatement();
if(!(t1 instanceof Production)){
agune/flyJenkins
flyJenkins/src/main/java/org/flyJenkins/component/agent/AgentManagerImpl.java
// Path: common/src/main/java/org/flyJenkins/agent/AgentManager.java // public interface AgentManager { // // /** // * register agnet when start agent // * @param Agent // * @return List<ServiceMeta> // */ // public List<ServiceMeta> register(Agent agent); // // /** // * complete starting of agent // * @param Agent // * @return boolean // */ // public boolean complete(Agent agent); // } // // Path: common/src/main/java/org/flyJenkins/model/Agent.java // public class Agent { // // } // // Path: common/src/main/java/org/flyJenkins/model/ServiceMeta.java // public class ServiceMeta { // /** // * Service Server host // */ // private String host; // // // /** // * deploy destination point // */ // private String destination; // // /** // * deploy type // */ // private int type; // // /** // * Service Server Group Id // */ // private int groupID; // // /** // * Service Server Id (auto increase) // */ // private int serviceID; // /** // * test cmd after deploy // */ // private String command; // // /** // * priority of deployment // */ // private int weight; // // // /** // * test url info // */ // private String testUrl; // // private Date createDate; // // public String getHost() { // return host; // } // // // public void setHost(String host) { // this.host = host; // } // // // public String getDestination() { // return destination; // } // // // public void setDestination(String destination) { // this.destination = destination; // } // // // public int getType() { // return type; // } // // // public void setType(int type) { // this.type = type; // } // // // public int getGroupID() { // return groupID; // } // // // public void setGroupID(int groupID) { // this.groupID = groupID; // } // // // public int getServiceID() { // return serviceID; // } // // // public void setServiceID(int serviceID) { // this.serviceID = serviceID; // } // // // public String getCommand() { // return command; // } // // // public void setCommand(String command) { // this.command = command; // } // // // public int getWeight() { // return weight; // } // // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getTestUrl() { // return testUrl; // } // // // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // }
import java.util.List; import org.flyJenkins.agent.AgentManager; import org.flyJenkins.model.Agent; import org.flyJenkins.model.ServiceMeta;
package org.flyJenkins.component.agent; public class AgentManagerImpl implements AgentManager { public boolean complete(Agent agent) { return false; }
// Path: common/src/main/java/org/flyJenkins/agent/AgentManager.java // public interface AgentManager { // // /** // * register agnet when start agent // * @param Agent // * @return List<ServiceMeta> // */ // public List<ServiceMeta> register(Agent agent); // // /** // * complete starting of agent // * @param Agent // * @return boolean // */ // public boolean complete(Agent agent); // } // // Path: common/src/main/java/org/flyJenkins/model/Agent.java // public class Agent { // // } // // Path: common/src/main/java/org/flyJenkins/model/ServiceMeta.java // public class ServiceMeta { // /** // * Service Server host // */ // private String host; // // // /** // * deploy destination point // */ // private String destination; // // /** // * deploy type // */ // private int type; // // /** // * Service Server Group Id // */ // private int groupID; // // /** // * Service Server Id (auto increase) // */ // private int serviceID; // /** // * test cmd after deploy // */ // private String command; // // /** // * priority of deployment // */ // private int weight; // // // /** // * test url info // */ // private String testUrl; // // private Date createDate; // // public String getHost() { // return host; // } // // // public void setHost(String host) { // this.host = host; // } // // // public String getDestination() { // return destination; // } // // // public void setDestination(String destination) { // this.destination = destination; // } // // // public int getType() { // return type; // } // // // public void setType(int type) { // this.type = type; // } // // // public int getGroupID() { // return groupID; // } // // // public void setGroupID(int groupID) { // this.groupID = groupID; // } // // // public int getServiceID() { // return serviceID; // } // // // public void setServiceID(int serviceID) { // this.serviceID = serviceID; // } // // // public String getCommand() { // return command; // } // // // public void setCommand(String command) { // this.command = command; // } // // // public int getWeight() { // return weight; // } // // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getTestUrl() { // return testUrl; // } // // // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // } // Path: flyJenkins/src/main/java/org/flyJenkins/component/agent/AgentManagerImpl.java import java.util.List; import org.flyJenkins.agent.AgentManager; import org.flyJenkins.model.Agent; import org.flyJenkins.model.ServiceMeta; package org.flyJenkins.component.agent; public class AgentManagerImpl implements AgentManager { public boolean complete(Agent agent) { return false; }
public List<ServiceMeta> register(Agent agent) {
agune/flyJenkins
flyJenkins/src/test/com/agun/flyJenkins/persistence/ServiceGroupSaveableTest.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ServiceGroup.java // public class ServiceGroup { // /** // * Service 의 Group Id // */ // private int groupId; // // /** // * Service Group Name; // */ // private String groupName; // // // private List<ServiceMeta> serviceMetaList = null; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public List<ServiceMeta> getServiceMetaList() { // return serviceMetaList; // } // // public void setServiceMetaList(List<ServiceMeta> serviceMetaList) { // this.serviceMetaList = serviceMetaList; // } // // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ServiceMeta.java // public class ServiceMeta { // // /** // * Service Server host // */ // private String host; // /** // * deploy destination point // */ // private String destination; // // /** // * deploy type // */ // private Integer type; // // /** // * Service Server Group Id // */ // private Integer groupId; // // /** // * Service Server Id (auto increase) // */ // private Integer serviceId; // /** // * test cmd after deploy // */ // private String command; // // /** // * priority of deployment // */ // private Integer weight; // /** // * process id of service app // */ // private Integer pid; // // /** // * process id of service name // */ // private String name; // // // /** // * test url info // */ // private String testUrl; // // // /** // * install able // */ // private boolean installAble; // // // private int dependenceService =0 ; // // // // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // // public String getDestination() { // return destination; // } // // // public void setDestination(String destination) { // this.destination = destination; // } // // // public Integer getType() { // return type; // } // // // public void setType(Integer type) { // this.type = type; // } // // // public Integer getGroupId() { // if(groupId == null) // return 0; // return groupId; // } // // // public void setGroupId(Integer groupId) { // this.groupId = groupId; // } // // // public Integer getServiceId() { // if(this.serviceId == null) // return 0; // // return this.serviceId; // } // // // public void setServiceId(Integer serviceId) { // this.serviceId = serviceId; // } // // // public String getCommand() { // return command; // } // // // public void setCommand(String command) { // this.command = command; // } // // // public Integer getWeight() { // return weight; // } // // // public void setWeight(Integer weight) { // this.weight = weight; // } // // // public Integer getPid() { // if(pid == null) // return 0; // return pid; // } // // // public void setPid(Integer pid) { // this.pid = pid; // } // // // public String getName() { // return name; // } // // // public void setName(String name) { // this.name = name; // } // // // public String getTestUrl() { // return testUrl; // } // // // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // // // public boolean isInstallAble() { // return installAble; // } // // // public void setInstallAble(boolean installAble) { // this.installAble = installAble; // } // // public int getDependenceService() { // return dependenceService; // } // // public void setDependenceService(int dependenceService) { // this.dependenceService = dependenceService; // } // // }
import static org.junit.Assert.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import jenkins.model.Jenkins; import org.junit.Test; import com.agun.flyJenkins.model.ServiceGroup; import com.agun.flyJenkins.model.ServiceMeta;
package com.agun.flyJenkins.persistence; public class ServiceGroupSaveableTest { @Test public void saveTest() { /** * create test service group data */
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ServiceGroup.java // public class ServiceGroup { // /** // * Service 의 Group Id // */ // private int groupId; // // /** // * Service Group Name; // */ // private String groupName; // // // private List<ServiceMeta> serviceMetaList = null; // // public int getGroupId() { // return groupId; // } // // public void setGroupId(int groupId) { // this.groupId = groupId; // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public List<ServiceMeta> getServiceMetaList() { // return serviceMetaList; // } // // public void setServiceMetaList(List<ServiceMeta> serviceMetaList) { // this.serviceMetaList = serviceMetaList; // } // // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ServiceMeta.java // public class ServiceMeta { // // /** // * Service Server host // */ // private String host; // /** // * deploy destination point // */ // private String destination; // // /** // * deploy type // */ // private Integer type; // // /** // * Service Server Group Id // */ // private Integer groupId; // // /** // * Service Server Id (auto increase) // */ // private Integer serviceId; // /** // * test cmd after deploy // */ // private String command; // // /** // * priority of deployment // */ // private Integer weight; // /** // * process id of service app // */ // private Integer pid; // // /** // * process id of service name // */ // private String name; // // // /** // * test url info // */ // private String testUrl; // // // /** // * install able // */ // private boolean installAble; // // // private int dependenceService =0 ; // // // // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // // public String getDestination() { // return destination; // } // // // public void setDestination(String destination) { // this.destination = destination; // } // // // public Integer getType() { // return type; // } // // // public void setType(Integer type) { // this.type = type; // } // // // public Integer getGroupId() { // if(groupId == null) // return 0; // return groupId; // } // // // public void setGroupId(Integer groupId) { // this.groupId = groupId; // } // // // public Integer getServiceId() { // if(this.serviceId == null) // return 0; // // return this.serviceId; // } // // // public void setServiceId(Integer serviceId) { // this.serviceId = serviceId; // } // // // public String getCommand() { // return command; // } // // // public void setCommand(String command) { // this.command = command; // } // // // public Integer getWeight() { // return weight; // } // // // public void setWeight(Integer weight) { // this.weight = weight; // } // // // public Integer getPid() { // if(pid == null) // return 0; // return pid; // } // // // public void setPid(Integer pid) { // this.pid = pid; // } // // // public String getName() { // return name; // } // // // public void setName(String name) { // this.name = name; // } // // // public String getTestUrl() { // return testUrl; // } // // // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // // // public boolean isInstallAble() { // return installAble; // } // // // public void setInstallAble(boolean installAble) { // this.installAble = installAble; // } // // public int getDependenceService() { // return dependenceService; // } // // public void setDependenceService(int dependenceService) { // this.dependenceService = dependenceService; // } // // } // Path: flyJenkins/src/test/com/agun/flyJenkins/persistence/ServiceGroupSaveableTest.java import static org.junit.Assert.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import jenkins.model.Jenkins; import org.junit.Test; import com.agun.flyJenkins.model.ServiceGroup; import com.agun.flyJenkins.model.ServiceMeta; package com.agun.flyJenkins.persistence; public class ServiceGroupSaveableTest { @Test public void saveTest() { /** * create test service group data */
ServiceGroup serviceGroup = createFacadeServiceGroup();
agune/flyJenkins
flyAgent/src/main/java/com/agun/flyJenkins/util/FlyJenkinsInfoManager.java
// Path: flyAgent/src/main/java/com/agun/agent/model/AgentMemoryStore.java // public class AgentMemoryStore { // // private static AgentMemoryStore agentMemory = new AgentMemoryStore(); // private List<AgentMeta> agentMetaList; // private FlyJenkinsInfo flyJenkinsInfo = null; // // public static AgentMemoryStore getInstance(){ // return agentMemory; // } // // private AgentMemoryStore(){ // agentMetaList = new ArrayList<AgentMeta>(); // } // // public void addAgentMeta(AgentMeta agentMeta){ // int agentId = delAgentMeta(agentMeta.getServiceId()); // if(agentId > 0) // agentMeta.setId(agentId); // this.agentMetaList.add(agentMeta); // } // // public List<AgentMeta> getAgentMetaList(){ // return this.agentMetaList; // } // // public AgentMeta getAgentMeta(int agentId){ // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getId() == agentId) // return agentMeta; // } // return null; // } // // public int getAgentTotalSize(){ // return agentMetaList.size(); // } // // public int delAgentMeta(int serviceId){ // int agentId = 0; // if(agentMetaList == null) // return 0; // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getServiceId() == serviceId){ // agentId = agentMeta.getId(); // agentMetaList.remove(agentMeta); // break; // } // } // return agentId; // } // // // public FlyJenkinsInfo getFlyJenkinsInfo() { // return flyJenkinsInfo; // } // // public void setFlyJenkinsInfo(FlyJenkinsInfo flyJenkinsInfo) { // this.flyJenkinsInfo = flyJenkinsInfo; // } // // // // } // // Path: flyAgent/src/main/java/com/agun/agent/model/FlyJenkinsInfo.java // public class FlyJenkinsInfo { // private String jenkinsHome = null; // private String flyJenkinsHome = null; // // // public String getJenkinsHome() { // return jenkinsHome; // } // // public void setJenkinsHome(String jenkinsHome) { // this.jenkinsHome = jenkinsHome; // } // // public String getFlyJenkinsHome() { // return flyJenkinsHome; // } // // public void setFlyJenkinsHome(String flyJenkinsHome) { // this.flyJenkinsHome = flyJenkinsHome; // } // }
import com.agun.agent.model.AgentMemoryStore; import com.agun.agent.model.FlyJenkinsInfo;
package com.agun.flyJenkins.util; public class FlyJenkinsInfoManager { public static String getLastBuldInfo(int serviceId){
// Path: flyAgent/src/main/java/com/agun/agent/model/AgentMemoryStore.java // public class AgentMemoryStore { // // private static AgentMemoryStore agentMemory = new AgentMemoryStore(); // private List<AgentMeta> agentMetaList; // private FlyJenkinsInfo flyJenkinsInfo = null; // // public static AgentMemoryStore getInstance(){ // return agentMemory; // } // // private AgentMemoryStore(){ // agentMetaList = new ArrayList<AgentMeta>(); // } // // public void addAgentMeta(AgentMeta agentMeta){ // int agentId = delAgentMeta(agentMeta.getServiceId()); // if(agentId > 0) // agentMeta.setId(agentId); // this.agentMetaList.add(agentMeta); // } // // public List<AgentMeta> getAgentMetaList(){ // return this.agentMetaList; // } // // public AgentMeta getAgentMeta(int agentId){ // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getId() == agentId) // return agentMeta; // } // return null; // } // // public int getAgentTotalSize(){ // return agentMetaList.size(); // } // // public int delAgentMeta(int serviceId){ // int agentId = 0; // if(agentMetaList == null) // return 0; // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getServiceId() == serviceId){ // agentId = agentMeta.getId(); // agentMetaList.remove(agentMeta); // break; // } // } // return agentId; // } // // // public FlyJenkinsInfo getFlyJenkinsInfo() { // return flyJenkinsInfo; // } // // public void setFlyJenkinsInfo(FlyJenkinsInfo flyJenkinsInfo) { // this.flyJenkinsInfo = flyJenkinsInfo; // } // // // // } // // Path: flyAgent/src/main/java/com/agun/agent/model/FlyJenkinsInfo.java // public class FlyJenkinsInfo { // private String jenkinsHome = null; // private String flyJenkinsHome = null; // // // public String getJenkinsHome() { // return jenkinsHome; // } // // public void setJenkinsHome(String jenkinsHome) { // this.jenkinsHome = jenkinsHome; // } // // public String getFlyJenkinsHome() { // return flyJenkinsHome; // } // // public void setFlyJenkinsHome(String flyJenkinsHome) { // this.flyJenkinsHome = flyJenkinsHome; // } // } // Path: flyAgent/src/main/java/com/agun/flyJenkins/util/FlyJenkinsInfoManager.java import com.agun.agent.model.AgentMemoryStore; import com.agun.agent.model.FlyJenkinsInfo; package com.agun.flyJenkins.util; public class FlyJenkinsInfoManager { public static String getLastBuldInfo(int serviceId){
AgentMemoryStore agentMeaMemoryStore = AgentMemoryStore.getInstance();
agune/flyJenkins
flyAgent/src/main/java/com/agun/flyJenkins/util/FlyJenkinsInfoManager.java
// Path: flyAgent/src/main/java/com/agun/agent/model/AgentMemoryStore.java // public class AgentMemoryStore { // // private static AgentMemoryStore agentMemory = new AgentMemoryStore(); // private List<AgentMeta> agentMetaList; // private FlyJenkinsInfo flyJenkinsInfo = null; // // public static AgentMemoryStore getInstance(){ // return agentMemory; // } // // private AgentMemoryStore(){ // agentMetaList = new ArrayList<AgentMeta>(); // } // // public void addAgentMeta(AgentMeta agentMeta){ // int agentId = delAgentMeta(agentMeta.getServiceId()); // if(agentId > 0) // agentMeta.setId(agentId); // this.agentMetaList.add(agentMeta); // } // // public List<AgentMeta> getAgentMetaList(){ // return this.agentMetaList; // } // // public AgentMeta getAgentMeta(int agentId){ // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getId() == agentId) // return agentMeta; // } // return null; // } // // public int getAgentTotalSize(){ // return agentMetaList.size(); // } // // public int delAgentMeta(int serviceId){ // int agentId = 0; // if(agentMetaList == null) // return 0; // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getServiceId() == serviceId){ // agentId = agentMeta.getId(); // agentMetaList.remove(agentMeta); // break; // } // } // return agentId; // } // // // public FlyJenkinsInfo getFlyJenkinsInfo() { // return flyJenkinsInfo; // } // // public void setFlyJenkinsInfo(FlyJenkinsInfo flyJenkinsInfo) { // this.flyJenkinsInfo = flyJenkinsInfo; // } // // // // } // // Path: flyAgent/src/main/java/com/agun/agent/model/FlyJenkinsInfo.java // public class FlyJenkinsInfo { // private String jenkinsHome = null; // private String flyJenkinsHome = null; // // // public String getJenkinsHome() { // return jenkinsHome; // } // // public void setJenkinsHome(String jenkinsHome) { // this.jenkinsHome = jenkinsHome; // } // // public String getFlyJenkinsHome() { // return flyJenkinsHome; // } // // public void setFlyJenkinsHome(String flyJenkinsHome) { // this.flyJenkinsHome = flyJenkinsHome; // } // }
import com.agun.agent.model.AgentMemoryStore; import com.agun.agent.model.FlyJenkinsInfo;
package com.agun.flyJenkins.util; public class FlyJenkinsInfoManager { public static String getLastBuldInfo(int serviceId){ AgentMemoryStore agentMeaMemoryStore = AgentMemoryStore.getInstance();
// Path: flyAgent/src/main/java/com/agun/agent/model/AgentMemoryStore.java // public class AgentMemoryStore { // // private static AgentMemoryStore agentMemory = new AgentMemoryStore(); // private List<AgentMeta> agentMetaList; // private FlyJenkinsInfo flyJenkinsInfo = null; // // public static AgentMemoryStore getInstance(){ // return agentMemory; // } // // private AgentMemoryStore(){ // agentMetaList = new ArrayList<AgentMeta>(); // } // // public void addAgentMeta(AgentMeta agentMeta){ // int agentId = delAgentMeta(agentMeta.getServiceId()); // if(agentId > 0) // agentMeta.setId(agentId); // this.agentMetaList.add(agentMeta); // } // // public List<AgentMeta> getAgentMetaList(){ // return this.agentMetaList; // } // // public AgentMeta getAgentMeta(int agentId){ // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getId() == agentId) // return agentMeta; // } // return null; // } // // public int getAgentTotalSize(){ // return agentMetaList.size(); // } // // public int delAgentMeta(int serviceId){ // int agentId = 0; // if(agentMetaList == null) // return 0; // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getServiceId() == serviceId){ // agentId = agentMeta.getId(); // agentMetaList.remove(agentMeta); // break; // } // } // return agentId; // } // // // public FlyJenkinsInfo getFlyJenkinsInfo() { // return flyJenkinsInfo; // } // // public void setFlyJenkinsInfo(FlyJenkinsInfo flyJenkinsInfo) { // this.flyJenkinsInfo = flyJenkinsInfo; // } // // // // } // // Path: flyAgent/src/main/java/com/agun/agent/model/FlyJenkinsInfo.java // public class FlyJenkinsInfo { // private String jenkinsHome = null; // private String flyJenkinsHome = null; // // // public String getJenkinsHome() { // return jenkinsHome; // } // // public void setJenkinsHome(String jenkinsHome) { // this.jenkinsHome = jenkinsHome; // } // // public String getFlyJenkinsHome() { // return flyJenkinsHome; // } // // public void setFlyJenkinsHome(String flyJenkinsHome) { // this.flyJenkinsHome = flyJenkinsHome; // } // } // Path: flyAgent/src/main/java/com/agun/flyJenkins/util/FlyJenkinsInfoManager.java import com.agun.agent.model.AgentMemoryStore; import com.agun.agent.model.FlyJenkinsInfo; package com.agun.flyJenkins.util; public class FlyJenkinsInfoManager { public static String getLastBuldInfo(int serviceId){ AgentMemoryStore agentMeaMemoryStore = AgentMemoryStore.getInstance();
FlyJenkinsInfo flyJenkinsInfo = agentMeaMemoryStore.getFlyJenkinsInfo();
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/persistence/DeployReportSaveableUtil.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/DeployReport.java // public class DeployReport { // // private String deployId; // private int deploySize = 0; // private int successCount =0; // private int failCount = 0; // // public String getDeployId() { // return deployId; // } // public void setDeployId(String deployId) { // this.deployId = deployId; // } // public int getDeploySize() { // return deploySize; // } // public void setDeploySize(int deploySize) { // this.deploySize = deploySize; // } // public int getSuccessCount() { // return successCount; // } // public void setSuccessCount(int successCount) { // this.successCount = successCount; // } // public int getFailCount() { // return failCount; // } // public void setFailCount(int failCount) { // this.failCount = failCount; // } // // public void plusSuccessCount(){ // this.successCount++; // } // // public void plusFailCount(){ // this.failCount++; // } // // public boolean isFinished(){ // if(deploySize == 0) // return true; // if(deploySize == (failCount + successCount)) // return true; // // return false; // } // // public int getNextOrder(){ // if(isFinished()){ // return 0; // } // // if(deploySize > (failCount + successCount)) // return failCount + successCount +1; // // return 0; // } // // }
import java.io.IOException; import java.util.List; import com.agun.flyJenkins.model.DeployReport;
package com.agun.flyJenkins.persistence; public class DeployReportSaveableUtil { public static void plusSuccessCount(String deployId){ DeployReportSaveable deployReportSaveable = new DeployReportSaveable(); deployReportSaveable.load();
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/DeployReport.java // public class DeployReport { // // private String deployId; // private int deploySize = 0; // private int successCount =0; // private int failCount = 0; // // public String getDeployId() { // return deployId; // } // public void setDeployId(String deployId) { // this.deployId = deployId; // } // public int getDeploySize() { // return deploySize; // } // public void setDeploySize(int deploySize) { // this.deploySize = deploySize; // } // public int getSuccessCount() { // return successCount; // } // public void setSuccessCount(int successCount) { // this.successCount = successCount; // } // public int getFailCount() { // return failCount; // } // public void setFailCount(int failCount) { // this.failCount = failCount; // } // // public void plusSuccessCount(){ // this.successCount++; // } // // public void plusFailCount(){ // this.failCount++; // } // // public boolean isFinished(){ // if(deploySize == 0) // return true; // if(deploySize == (failCount + successCount)) // return true; // // return false; // } // // public int getNextOrder(){ // if(isFinished()){ // return 0; // } // // if(deploySize > (failCount + successCount)) // return failCount + successCount +1; // // return 0; // } // // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/DeployReportSaveableUtil.java import java.io.IOException; import java.util.List; import com.agun.flyJenkins.model.DeployReport; package com.agun.flyJenkins.persistence; public class DeployReportSaveableUtil { public static void plusSuccessCount(String deployId){ DeployReportSaveable deployReportSaveable = new DeployReportSaveable(); deployReportSaveable.load();
List<DeployReport> deployReportList = deployReportSaveable.getDeployReportList();
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/ui/ProductionList.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ProductionMeta.java // public class ProductionMeta { // // private String jobName; // private Date createDate; // private String productionPath; // private String productionPathOfJob; // private int serviceGroup; // private int buildNumber; // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public int getBuildNumber() { // return buildNumber; // } // // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public int getServiceGroup() { // return serviceGroup; // } // // public void setServiceGroup(int serviceGroup) { // this.serviceGroup = serviceGroup; // } // // public String getProductionPath() { // return productionPath; // } // // public void setProductionPath(String productionPath) { // this.productionPath = productionPath; // } // // public String getProductionPathOfJob() { // return productionPathOfJob; // } // // public void setProductionPathOfJob(String productionPathOfJob) { // this.productionPathOfJob = productionPathOfJob; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/ProductionSaveable.java // public class ProductionSaveable implements Saveable{ // // List<ProductionMeta> productionMetaList = null; // // public void save() throws IOException { // if(productionMetaList != null){ // ModelSoting.productionSortDate(productionMetaList); // } // if(BulkChange.contains(this)) return; // try { // getConfigFile().write(this); // SaveableListener.fireOnChange(this, getConfigFile()); // } catch (IOException e) { // e.printStackTrace(); // } // // } // protected XmlFile getConfigFile() { // // return new XmlFile(new File(Jenkins.getInstance().getRootDir(), this.getClass().getSimpleName()+".xml")); // } // // // /** // * open file and load data // */ // public synchronized void load() { // XmlFile file = getConfigFile(); // if(!file.exists()) // return; // try { // file.unmarshal(this); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<ProductionMeta> getProductionMetaList() { // return productionMetaList; // } // // public void setProductionMetaList(List<ProductionMeta> productionMetaList) { // this.productionMetaList = productionMetaList; // } // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.agun.flyJenkins.model.ProductionMeta; import com.agun.flyJenkins.persistence.ProductionSaveable; import hudson.Extension;
package com.agun.flyJenkins.ui; @Extension public class ProductionList extends FlyUI { @Override public String getDescription() { return "production list"; }
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ProductionMeta.java // public class ProductionMeta { // // private String jobName; // private Date createDate; // private String productionPath; // private String productionPathOfJob; // private int serviceGroup; // private int buildNumber; // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public int getBuildNumber() { // return buildNumber; // } // // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public int getServiceGroup() { // return serviceGroup; // } // // public void setServiceGroup(int serviceGroup) { // this.serviceGroup = serviceGroup; // } // // public String getProductionPath() { // return productionPath; // } // // public void setProductionPath(String productionPath) { // this.productionPath = productionPath; // } // // public String getProductionPathOfJob() { // return productionPathOfJob; // } // // public void setProductionPathOfJob(String productionPathOfJob) { // this.productionPathOfJob = productionPathOfJob; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/ProductionSaveable.java // public class ProductionSaveable implements Saveable{ // // List<ProductionMeta> productionMetaList = null; // // public void save() throws IOException { // if(productionMetaList != null){ // ModelSoting.productionSortDate(productionMetaList); // } // if(BulkChange.contains(this)) return; // try { // getConfigFile().write(this); // SaveableListener.fireOnChange(this, getConfigFile()); // } catch (IOException e) { // e.printStackTrace(); // } // // } // protected XmlFile getConfigFile() { // // return new XmlFile(new File(Jenkins.getInstance().getRootDir(), this.getClass().getSimpleName()+".xml")); // } // // // /** // * open file and load data // */ // public synchronized void load() { // XmlFile file = getConfigFile(); // if(!file.exists()) // return; // try { // file.unmarshal(this); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<ProductionMeta> getProductionMetaList() { // return productionMetaList; // } // // public void setProductionMetaList(List<ProductionMeta> productionMetaList) { // this.productionMetaList = productionMetaList; // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/ui/ProductionList.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.agun.flyJenkins.model.ProductionMeta; import com.agun.flyJenkins.persistence.ProductionSaveable; import hudson.Extension; package com.agun.flyJenkins.ui; @Extension public class ProductionList extends FlyUI { @Override public String getDescription() { return "production list"; }
public List<ProductionMeta> getProductionMetaList(String jobName){
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/ui/ProductionList.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ProductionMeta.java // public class ProductionMeta { // // private String jobName; // private Date createDate; // private String productionPath; // private String productionPathOfJob; // private int serviceGroup; // private int buildNumber; // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public int getBuildNumber() { // return buildNumber; // } // // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public int getServiceGroup() { // return serviceGroup; // } // // public void setServiceGroup(int serviceGroup) { // this.serviceGroup = serviceGroup; // } // // public String getProductionPath() { // return productionPath; // } // // public void setProductionPath(String productionPath) { // this.productionPath = productionPath; // } // // public String getProductionPathOfJob() { // return productionPathOfJob; // } // // public void setProductionPathOfJob(String productionPathOfJob) { // this.productionPathOfJob = productionPathOfJob; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/ProductionSaveable.java // public class ProductionSaveable implements Saveable{ // // List<ProductionMeta> productionMetaList = null; // // public void save() throws IOException { // if(productionMetaList != null){ // ModelSoting.productionSortDate(productionMetaList); // } // if(BulkChange.contains(this)) return; // try { // getConfigFile().write(this); // SaveableListener.fireOnChange(this, getConfigFile()); // } catch (IOException e) { // e.printStackTrace(); // } // // } // protected XmlFile getConfigFile() { // // return new XmlFile(new File(Jenkins.getInstance().getRootDir(), this.getClass().getSimpleName()+".xml")); // } // // // /** // * open file and load data // */ // public synchronized void load() { // XmlFile file = getConfigFile(); // if(!file.exists()) // return; // try { // file.unmarshal(this); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<ProductionMeta> getProductionMetaList() { // return productionMetaList; // } // // public void setProductionMetaList(List<ProductionMeta> productionMetaList) { // this.productionMetaList = productionMetaList; // } // }
import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.agun.flyJenkins.model.ProductionMeta; import com.agun.flyJenkins.persistence.ProductionSaveable; import hudson.Extension;
package com.agun.flyJenkins.ui; @Extension public class ProductionList extends FlyUI { @Override public String getDescription() { return "production list"; } public List<ProductionMeta> getProductionMetaList(String jobName){
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/ProductionMeta.java // public class ProductionMeta { // // private String jobName; // private Date createDate; // private String productionPath; // private String productionPathOfJob; // private int serviceGroup; // private int buildNumber; // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public int getBuildNumber() { // return buildNumber; // } // // public void setBuildNumber(int buildNumber) { // this.buildNumber = buildNumber; // } // // public Date getCreateDate() { // return createDate; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public int getServiceGroup() { // return serviceGroup; // } // // public void setServiceGroup(int serviceGroup) { // this.serviceGroup = serviceGroup; // } // // public String getProductionPath() { // return productionPath; // } // // public void setProductionPath(String productionPath) { // this.productionPath = productionPath; // } // // public String getProductionPathOfJob() { // return productionPathOfJob; // } // // public void setProductionPathOfJob(String productionPathOfJob) { // this.productionPathOfJob = productionPathOfJob; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/ProductionSaveable.java // public class ProductionSaveable implements Saveable{ // // List<ProductionMeta> productionMetaList = null; // // public void save() throws IOException { // if(productionMetaList != null){ // ModelSoting.productionSortDate(productionMetaList); // } // if(BulkChange.contains(this)) return; // try { // getConfigFile().write(this); // SaveableListener.fireOnChange(this, getConfigFile()); // } catch (IOException e) { // e.printStackTrace(); // } // // } // protected XmlFile getConfigFile() { // // return new XmlFile(new File(Jenkins.getInstance().getRootDir(), this.getClass().getSimpleName()+".xml")); // } // // // /** // * open file and load data // */ // public synchronized void load() { // XmlFile file = getConfigFile(); // if(!file.exists()) // return; // try { // file.unmarshal(this); // } catch (IOException e) { // e.printStackTrace(); // } // } // // public List<ProductionMeta> getProductionMetaList() { // return productionMetaList; // } // // public void setProductionMetaList(List<ProductionMeta> productionMetaList) { // this.productionMetaList = productionMetaList; // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/ui/ProductionList.java import java.util.ArrayList; import java.util.Collections; import java.util.List; import com.agun.flyJenkins.model.ProductionMeta; import com.agun.flyJenkins.persistence.ProductionSaveable; import hudson.Extension; package com.agun.flyJenkins.ui; @Extension public class ProductionList extends FlyUI { @Override public String getDescription() { return "production list"; } public List<ProductionMeta> getProductionMetaList(String jobName){
ProductionSaveable productionSaveable = new ProductionSaveable();
agune/flyJenkins
flyAgent/src/main/java/com/agun/jenkins/CLICallable.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/process/FlyProcess.java // public interface FlyProcess { // public Map<String, Object> run(Object arg1, String operName); // }
import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import com.agun.flyJenkins.process.FlyProcess; import jenkins.model.Jenkins; import hudson.model.Action; import hudson.remoting.Callable;
package com.agun.jenkins; public class CLICallable implements Callable<Map<String, Object>, Throwable> { private String operationName; private String processName; private Object arg1; public Object getArg1() { return arg1; } public void setArg1(Object arg1) { this.arg1 = arg1; } public void setProcessName(String processName) { this.processName = processName; } public String getProcessName() { return processName; } public String getOperationName() { return operationName; } public void setOperationName(String operationName) { this.operationName = operationName; } @Override public Map<String, Object> call() throws Throwable { List<Action> actionList = Jenkins.getInstance().getActions(); for(Action action : actionList){ if(action.getDisplayName() != null && action.getDisplayName().equals("flyJenkins")){ try { Method method = action.getClass().getMethod("getFlyProcess", String.class);
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/process/FlyProcess.java // public interface FlyProcess { // public Map<String, Object> run(Object arg1, String operName); // } // Path: flyAgent/src/main/java/com/agun/jenkins/CLICallable.java import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import com.agun.flyJenkins.process.FlyProcess; import jenkins.model.Jenkins; import hudson.model.Action; import hudson.remoting.Callable; package com.agun.jenkins; public class CLICallable implements Callable<Map<String, Object>, Throwable> { private String operationName; private String processName; private Object arg1; public Object getArg1() { return arg1; } public void setArg1(Object arg1) { this.arg1 = arg1; } public void setProcessName(String processName) { this.processName = processName; } public String getProcessName() { return processName; } public String getOperationName() { return operationName; } public void setOperationName(String operationName) { this.operationName = operationName; } @Override public Map<String, Object> call() throws Throwable { List<Action> actionList = Jenkins.getInstance().getActions(); for(Action action : actionList){ if(action.getDisplayName() != null && action.getDisplayName().equals("flyJenkins")){ try { Method method = action.getClass().getMethod("getFlyProcess", String.class);
FlyProcess flyProcess = (FlyProcess) method.invoke(action, processName);
agune/flyJenkins
common/src/test/java/org/flyJenkins/model/store/ServiceStoreTest.java
// Path: common/src/main/java/org/flyJenkins/model/ServiceGroup.java // public class ServiceGroup { // // private int groupID; // private String name; // private Date createDate; // // private List<ServiceMeta> serviceMetaList; // // public int getGroupID() { // return groupID; // } // public void setGroupID(int groupID) { // this.groupID = groupID; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public List<ServiceMeta> getServiceMetaList() { // return serviceMetaList; // } // public void setServiceMetaList(List<ServiceMeta> serviceMetaList) { // this.serviceMetaList = serviceMetaList; // } // } // // Path: common/src/main/java/org/flyJenkins/model/ServiceMeta.java // public class ServiceMeta { // /** // * Service Server host // */ // private String host; // // // /** // * deploy destination point // */ // private String destination; // // /** // * deploy type // */ // private int type; // // /** // * Service Server Group Id // */ // private int groupID; // // /** // * Service Server Id (auto increase) // */ // private int serviceID; // /** // * test cmd after deploy // */ // private String command; // // /** // * priority of deployment // */ // private int weight; // // // /** // * test url info // */ // private String testUrl; // // private Date createDate; // // public String getHost() { // return host; // } // // // public void setHost(String host) { // this.host = host; // } // // // public String getDestination() { // return destination; // } // // // public void setDestination(String destination) { // this.destination = destination; // } // // // public int getType() { // return type; // } // // // public void setType(int type) { // this.type = type; // } // // // public int getGroupID() { // return groupID; // } // // // public void setGroupID(int groupID) { // this.groupID = groupID; // } // // // public int getServiceID() { // return serviceID; // } // // // public void setServiceID(int serviceID) { // this.serviceID = serviceID; // } // // // public String getCommand() { // return command; // } // // // public void setCommand(String command) { // this.command = command; // } // // // public int getWeight() { // return weight; // } // // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getTestUrl() { // return testUrl; // } // // // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // }
import static org.junit.Assert.*; import java.util.List; import org.flyJenkins.model.ServiceGroup; import org.flyJenkins.model.ServiceMeta; import org.junit.Test;
package org.flyJenkins.model.store; public class ServiceStoreTest { @Test public void storeTest() { ServiceStore serviceStore = new ServiceStore();
// Path: common/src/main/java/org/flyJenkins/model/ServiceGroup.java // public class ServiceGroup { // // private int groupID; // private String name; // private Date createDate; // // private List<ServiceMeta> serviceMetaList; // // public int getGroupID() { // return groupID; // } // public void setGroupID(int groupID) { // this.groupID = groupID; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public List<ServiceMeta> getServiceMetaList() { // return serviceMetaList; // } // public void setServiceMetaList(List<ServiceMeta> serviceMetaList) { // this.serviceMetaList = serviceMetaList; // } // } // // Path: common/src/main/java/org/flyJenkins/model/ServiceMeta.java // public class ServiceMeta { // /** // * Service Server host // */ // private String host; // // // /** // * deploy destination point // */ // private String destination; // // /** // * deploy type // */ // private int type; // // /** // * Service Server Group Id // */ // private int groupID; // // /** // * Service Server Id (auto increase) // */ // private int serviceID; // /** // * test cmd after deploy // */ // private String command; // // /** // * priority of deployment // */ // private int weight; // // // /** // * test url info // */ // private String testUrl; // // private Date createDate; // // public String getHost() { // return host; // } // // // public void setHost(String host) { // this.host = host; // } // // // public String getDestination() { // return destination; // } // // // public void setDestination(String destination) { // this.destination = destination; // } // // // public int getType() { // return type; // } // // // public void setType(int type) { // this.type = type; // } // // // public int getGroupID() { // return groupID; // } // // // public void setGroupID(int groupID) { // this.groupID = groupID; // } // // // public int getServiceID() { // return serviceID; // } // // // public void setServiceID(int serviceID) { // this.serviceID = serviceID; // } // // // public String getCommand() { // return command; // } // // // public void setCommand(String command) { // this.command = command; // } // // // public int getWeight() { // return weight; // } // // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getTestUrl() { // return testUrl; // } // // // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // } // Path: common/src/test/java/org/flyJenkins/model/store/ServiceStoreTest.java import static org.junit.Assert.*; import java.util.List; import org.flyJenkins.model.ServiceGroup; import org.flyJenkins.model.ServiceMeta; import org.junit.Test; package org.flyJenkins.model.store; public class ServiceStoreTest { @Test public void storeTest() { ServiceStore serviceStore = new ServiceStore();
ServiceGroup serviceGroup = new ServiceGroup();
agune/flyJenkins
common/src/test/java/org/flyJenkins/model/store/ServiceStoreTest.java
// Path: common/src/main/java/org/flyJenkins/model/ServiceGroup.java // public class ServiceGroup { // // private int groupID; // private String name; // private Date createDate; // // private List<ServiceMeta> serviceMetaList; // // public int getGroupID() { // return groupID; // } // public void setGroupID(int groupID) { // this.groupID = groupID; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public List<ServiceMeta> getServiceMetaList() { // return serviceMetaList; // } // public void setServiceMetaList(List<ServiceMeta> serviceMetaList) { // this.serviceMetaList = serviceMetaList; // } // } // // Path: common/src/main/java/org/flyJenkins/model/ServiceMeta.java // public class ServiceMeta { // /** // * Service Server host // */ // private String host; // // // /** // * deploy destination point // */ // private String destination; // // /** // * deploy type // */ // private int type; // // /** // * Service Server Group Id // */ // private int groupID; // // /** // * Service Server Id (auto increase) // */ // private int serviceID; // /** // * test cmd after deploy // */ // private String command; // // /** // * priority of deployment // */ // private int weight; // // // /** // * test url info // */ // private String testUrl; // // private Date createDate; // // public String getHost() { // return host; // } // // // public void setHost(String host) { // this.host = host; // } // // // public String getDestination() { // return destination; // } // // // public void setDestination(String destination) { // this.destination = destination; // } // // // public int getType() { // return type; // } // // // public void setType(int type) { // this.type = type; // } // // // public int getGroupID() { // return groupID; // } // // // public void setGroupID(int groupID) { // this.groupID = groupID; // } // // // public int getServiceID() { // return serviceID; // } // // // public void setServiceID(int serviceID) { // this.serviceID = serviceID; // } // // // public String getCommand() { // return command; // } // // // public void setCommand(String command) { // this.command = command; // } // // // public int getWeight() { // return weight; // } // // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getTestUrl() { // return testUrl; // } // // // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // }
import static org.junit.Assert.*; import java.util.List; import org.flyJenkins.model.ServiceGroup; import org.flyJenkins.model.ServiceMeta; import org.junit.Test;
package org.flyJenkins.model.store; public class ServiceStoreTest { @Test public void storeTest() { ServiceStore serviceStore = new ServiceStore(); ServiceGroup serviceGroup = new ServiceGroup(); serviceGroup.setGroupID(1); serviceGroup.setName("group1"); ServiceGroup serviceGroup2 = new ServiceGroup(); serviceGroup2.setGroupID(2); serviceGroup2.setName("group2"); serviceStore.storeGroup(serviceGroup); serviceStore.storeGroup(serviceGroup2); ServiceGroup groupResult = serviceStore.getGroupByID(1); assertTrue("not match group id", groupResult.getGroupID() == 1); assertTrue("not match group name", groupResult.getName().equals("group1") ); groupResult = serviceStore.getGroupByID(2); assertTrue("not match group id2", groupResult.getGroupID() == 2); assertTrue("not match group name2", groupResult.getName().equals("group2") ); // service assert start
// Path: common/src/main/java/org/flyJenkins/model/ServiceGroup.java // public class ServiceGroup { // // private int groupID; // private String name; // private Date createDate; // // private List<ServiceMeta> serviceMetaList; // // public int getGroupID() { // return groupID; // } // public void setGroupID(int groupID) { // this.groupID = groupID; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public List<ServiceMeta> getServiceMetaList() { // return serviceMetaList; // } // public void setServiceMetaList(List<ServiceMeta> serviceMetaList) { // this.serviceMetaList = serviceMetaList; // } // } // // Path: common/src/main/java/org/flyJenkins/model/ServiceMeta.java // public class ServiceMeta { // /** // * Service Server host // */ // private String host; // // // /** // * deploy destination point // */ // private String destination; // // /** // * deploy type // */ // private int type; // // /** // * Service Server Group Id // */ // private int groupID; // // /** // * Service Server Id (auto increase) // */ // private int serviceID; // /** // * test cmd after deploy // */ // private String command; // // /** // * priority of deployment // */ // private int weight; // // // /** // * test url info // */ // private String testUrl; // // private Date createDate; // // public String getHost() { // return host; // } // // // public void setHost(String host) { // this.host = host; // } // // // public String getDestination() { // return destination; // } // // // public void setDestination(String destination) { // this.destination = destination; // } // // // public int getType() { // return type; // } // // // public void setType(int type) { // this.type = type; // } // // // public int getGroupID() { // return groupID; // } // // // public void setGroupID(int groupID) { // this.groupID = groupID; // } // // // public int getServiceID() { // return serviceID; // } // // // public void setServiceID(int serviceID) { // this.serviceID = serviceID; // } // // // public String getCommand() { // return command; // } // // // public void setCommand(String command) { // this.command = command; // } // // // public int getWeight() { // return weight; // } // // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getTestUrl() { // return testUrl; // } // // // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // } // Path: common/src/test/java/org/flyJenkins/model/store/ServiceStoreTest.java import static org.junit.Assert.*; import java.util.List; import org.flyJenkins.model.ServiceGroup; import org.flyJenkins.model.ServiceMeta; import org.junit.Test; package org.flyJenkins.model.store; public class ServiceStoreTest { @Test public void storeTest() { ServiceStore serviceStore = new ServiceStore(); ServiceGroup serviceGroup = new ServiceGroup(); serviceGroup.setGroupID(1); serviceGroup.setName("group1"); ServiceGroup serviceGroup2 = new ServiceGroup(); serviceGroup2.setGroupID(2); serviceGroup2.setName("group2"); serviceStore.storeGroup(serviceGroup); serviceStore.storeGroup(serviceGroup2); ServiceGroup groupResult = serviceStore.getGroupByID(1); assertTrue("not match group id", groupResult.getGroupID() == 1); assertTrue("not match group name", groupResult.getName().equals("group1") ); groupResult = serviceStore.getGroupByID(2); assertTrue("not match group id2", groupResult.getGroupID() == 2); assertTrue("not match group name2", groupResult.getName().equals("group2") ); // service assert start
ServiceMeta serviceMeta = new ServiceMeta();
agune/flyJenkins
flyAgent/src/main/java/com/agun/system/AgentInfoManager.java
// Path: flyAgent/src/main/java/com/agun/agent/model/AgentMemoryStore.java // public class AgentMemoryStore { // // private static AgentMemoryStore agentMemory = new AgentMemoryStore(); // private List<AgentMeta> agentMetaList; // private FlyJenkinsInfo flyJenkinsInfo = null; // // public static AgentMemoryStore getInstance(){ // return agentMemory; // } // // private AgentMemoryStore(){ // agentMetaList = new ArrayList<AgentMeta>(); // } // // public void addAgentMeta(AgentMeta agentMeta){ // int agentId = delAgentMeta(agentMeta.getServiceId()); // if(agentId > 0) // agentMeta.setId(agentId); // this.agentMetaList.add(agentMeta); // } // // public List<AgentMeta> getAgentMetaList(){ // return this.agentMetaList; // } // // public AgentMeta getAgentMeta(int agentId){ // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getId() == agentId) // return agentMeta; // } // return null; // } // // public int getAgentTotalSize(){ // return agentMetaList.size(); // } // // public int delAgentMeta(int serviceId){ // int agentId = 0; // if(agentMetaList == null) // return 0; // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getServiceId() == serviceId){ // agentId = agentMeta.getId(); // agentMetaList.remove(agentMeta); // break; // } // } // return agentId; // } // // // public FlyJenkinsInfo getFlyJenkinsInfo() { // return flyJenkinsInfo; // } // // public void setFlyJenkinsInfo(FlyJenkinsInfo flyJenkinsInfo) { // this.flyJenkinsInfo = flyJenkinsInfo; // } // // // // } // // Path: flyAgent/src/main/java/com/agun/agent/model/AgentMeta.java // public class AgentMeta { // // private int id; // private int type; // private int pid; // private int serviceId; // // private String command; // private String testUrl; // // private String destination; // // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getDestination() { // return destination; // } // public void setDestination(String destination) { // this.destination = destination; // } // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public int getPid() { // return pid; // } // public void setPid(int pid) { // this.pid = pid; // } // public String getCommand() { // return command; // } // public void setCommand(String command) { // this.command = command; // } // public int getServiceId() { // return serviceId; // } // public void setServiceId(int serviceId) { // this.serviceId = serviceId; // } // public String getTestUrl() { // return testUrl; // } // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // }
import hudson.FilePath; import java.io.File; import java.io.IOException; import java.util.List; import com.agun.agent.model.AgentMemoryStore; import com.agun.agent.model.AgentMeta;
package com.agun.system; public class AgentInfoManager { public static String getAgnetHome(){ String agentHome = System.getenv("FLY_AGENT_HOME"); if(agentHome == null) return "."; return agentHome; } public static String getProductionPath(int serverId, String productionPath){ return AgentInfoManager.getAgnetHome() + "/production/" + serverId + "/" + productionPath; } public static void checkProductionDir(int serverId){ String tagret = AgentInfoManager.getAgnetHome() + "/production/" + serverId; FilePath filePath = new FilePath(new File(tagret)); try { if(filePath.exists() == false){ filePath.mkdirs(); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } public static int getAgentMaxId(){
// Path: flyAgent/src/main/java/com/agun/agent/model/AgentMemoryStore.java // public class AgentMemoryStore { // // private static AgentMemoryStore agentMemory = new AgentMemoryStore(); // private List<AgentMeta> agentMetaList; // private FlyJenkinsInfo flyJenkinsInfo = null; // // public static AgentMemoryStore getInstance(){ // return agentMemory; // } // // private AgentMemoryStore(){ // agentMetaList = new ArrayList<AgentMeta>(); // } // // public void addAgentMeta(AgentMeta agentMeta){ // int agentId = delAgentMeta(agentMeta.getServiceId()); // if(agentId > 0) // agentMeta.setId(agentId); // this.agentMetaList.add(agentMeta); // } // // public List<AgentMeta> getAgentMetaList(){ // return this.agentMetaList; // } // // public AgentMeta getAgentMeta(int agentId){ // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getId() == agentId) // return agentMeta; // } // return null; // } // // public int getAgentTotalSize(){ // return agentMetaList.size(); // } // // public int delAgentMeta(int serviceId){ // int agentId = 0; // if(agentMetaList == null) // return 0; // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getServiceId() == serviceId){ // agentId = agentMeta.getId(); // agentMetaList.remove(agentMeta); // break; // } // } // return agentId; // } // // // public FlyJenkinsInfo getFlyJenkinsInfo() { // return flyJenkinsInfo; // } // // public void setFlyJenkinsInfo(FlyJenkinsInfo flyJenkinsInfo) { // this.flyJenkinsInfo = flyJenkinsInfo; // } // // // // } // // Path: flyAgent/src/main/java/com/agun/agent/model/AgentMeta.java // public class AgentMeta { // // private int id; // private int type; // private int pid; // private int serviceId; // // private String command; // private String testUrl; // // private String destination; // // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getDestination() { // return destination; // } // public void setDestination(String destination) { // this.destination = destination; // } // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public int getPid() { // return pid; // } // public void setPid(int pid) { // this.pid = pid; // } // public String getCommand() { // return command; // } // public void setCommand(String command) { // this.command = command; // } // public int getServiceId() { // return serviceId; // } // public void setServiceId(int serviceId) { // this.serviceId = serviceId; // } // public String getTestUrl() { // return testUrl; // } // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // } // Path: flyAgent/src/main/java/com/agun/system/AgentInfoManager.java import hudson.FilePath; import java.io.File; import java.io.IOException; import java.util.List; import com.agun.agent.model.AgentMemoryStore; import com.agun.agent.model.AgentMeta; package com.agun.system; public class AgentInfoManager { public static String getAgnetHome(){ String agentHome = System.getenv("FLY_AGENT_HOME"); if(agentHome == null) return "."; return agentHome; } public static String getProductionPath(int serverId, String productionPath){ return AgentInfoManager.getAgnetHome() + "/production/" + serverId + "/" + productionPath; } public static void checkProductionDir(int serverId){ String tagret = AgentInfoManager.getAgnetHome() + "/production/" + serverId; FilePath filePath = new FilePath(new File(tagret)); try { if(filePath.exists() == false){ filePath.mkdirs(); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } public static int getAgentMaxId(){
AgentMemoryStore agentMemoryStore = AgentMemoryStore.getInstance();
agune/flyJenkins
flyAgent/src/main/java/com/agun/system/AgentInfoManager.java
// Path: flyAgent/src/main/java/com/agun/agent/model/AgentMemoryStore.java // public class AgentMemoryStore { // // private static AgentMemoryStore agentMemory = new AgentMemoryStore(); // private List<AgentMeta> agentMetaList; // private FlyJenkinsInfo flyJenkinsInfo = null; // // public static AgentMemoryStore getInstance(){ // return agentMemory; // } // // private AgentMemoryStore(){ // agentMetaList = new ArrayList<AgentMeta>(); // } // // public void addAgentMeta(AgentMeta agentMeta){ // int agentId = delAgentMeta(agentMeta.getServiceId()); // if(agentId > 0) // agentMeta.setId(agentId); // this.agentMetaList.add(agentMeta); // } // // public List<AgentMeta> getAgentMetaList(){ // return this.agentMetaList; // } // // public AgentMeta getAgentMeta(int agentId){ // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getId() == agentId) // return agentMeta; // } // return null; // } // // public int getAgentTotalSize(){ // return agentMetaList.size(); // } // // public int delAgentMeta(int serviceId){ // int agentId = 0; // if(agentMetaList == null) // return 0; // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getServiceId() == serviceId){ // agentId = agentMeta.getId(); // agentMetaList.remove(agentMeta); // break; // } // } // return agentId; // } // // // public FlyJenkinsInfo getFlyJenkinsInfo() { // return flyJenkinsInfo; // } // // public void setFlyJenkinsInfo(FlyJenkinsInfo flyJenkinsInfo) { // this.flyJenkinsInfo = flyJenkinsInfo; // } // // // // } // // Path: flyAgent/src/main/java/com/agun/agent/model/AgentMeta.java // public class AgentMeta { // // private int id; // private int type; // private int pid; // private int serviceId; // // private String command; // private String testUrl; // // private String destination; // // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getDestination() { // return destination; // } // public void setDestination(String destination) { // this.destination = destination; // } // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public int getPid() { // return pid; // } // public void setPid(int pid) { // this.pid = pid; // } // public String getCommand() { // return command; // } // public void setCommand(String command) { // this.command = command; // } // public int getServiceId() { // return serviceId; // } // public void setServiceId(int serviceId) { // this.serviceId = serviceId; // } // public String getTestUrl() { // return testUrl; // } // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // }
import hudson.FilePath; import java.io.File; import java.io.IOException; import java.util.List; import com.agun.agent.model.AgentMemoryStore; import com.agun.agent.model.AgentMeta;
package com.agun.system; public class AgentInfoManager { public static String getAgnetHome(){ String agentHome = System.getenv("FLY_AGENT_HOME"); if(agentHome == null) return "."; return agentHome; } public static String getProductionPath(int serverId, String productionPath){ return AgentInfoManager.getAgnetHome() + "/production/" + serverId + "/" + productionPath; } public static void checkProductionDir(int serverId){ String tagret = AgentInfoManager.getAgnetHome() + "/production/" + serverId; FilePath filePath = new FilePath(new File(tagret)); try { if(filePath.exists() == false){ filePath.mkdirs(); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } public static int getAgentMaxId(){ AgentMemoryStore agentMemoryStore = AgentMemoryStore.getInstance();
// Path: flyAgent/src/main/java/com/agun/agent/model/AgentMemoryStore.java // public class AgentMemoryStore { // // private static AgentMemoryStore agentMemory = new AgentMemoryStore(); // private List<AgentMeta> agentMetaList; // private FlyJenkinsInfo flyJenkinsInfo = null; // // public static AgentMemoryStore getInstance(){ // return agentMemory; // } // // private AgentMemoryStore(){ // agentMetaList = new ArrayList<AgentMeta>(); // } // // public void addAgentMeta(AgentMeta agentMeta){ // int agentId = delAgentMeta(agentMeta.getServiceId()); // if(agentId > 0) // agentMeta.setId(agentId); // this.agentMetaList.add(agentMeta); // } // // public List<AgentMeta> getAgentMetaList(){ // return this.agentMetaList; // } // // public AgentMeta getAgentMeta(int agentId){ // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getId() == agentId) // return agentMeta; // } // return null; // } // // public int getAgentTotalSize(){ // return agentMetaList.size(); // } // // public int delAgentMeta(int serviceId){ // int agentId = 0; // if(agentMetaList == null) // return 0; // for(AgentMeta agentMeta : agentMetaList){ // if(agentMeta.getServiceId() == serviceId){ // agentId = agentMeta.getId(); // agentMetaList.remove(agentMeta); // break; // } // } // return agentId; // } // // // public FlyJenkinsInfo getFlyJenkinsInfo() { // return flyJenkinsInfo; // } // // public void setFlyJenkinsInfo(FlyJenkinsInfo flyJenkinsInfo) { // this.flyJenkinsInfo = flyJenkinsInfo; // } // // // // } // // Path: flyAgent/src/main/java/com/agun/agent/model/AgentMeta.java // public class AgentMeta { // // private int id; // private int type; // private int pid; // private int serviceId; // // private String command; // private String testUrl; // // private String destination; // // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getDestination() { // return destination; // } // public void setDestination(String destination) { // this.destination = destination; // } // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public int getPid() { // return pid; // } // public void setPid(int pid) { // this.pid = pid; // } // public String getCommand() { // return command; // } // public void setCommand(String command) { // this.command = command; // } // public int getServiceId() { // return serviceId; // } // public void setServiceId(int serviceId) { // this.serviceId = serviceId; // } // public String getTestUrl() { // return testUrl; // } // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // } // Path: flyAgent/src/main/java/com/agun/system/AgentInfoManager.java import hudson.FilePath; import java.io.File; import java.io.IOException; import java.util.List; import com.agun.agent.model.AgentMemoryStore; import com.agun.agent.model.AgentMeta; package com.agun.system; public class AgentInfoManager { public static String getAgnetHome(){ String agentHome = System.getenv("FLY_AGENT_HOME"); if(agentHome == null) return "."; return agentHome; } public static String getProductionPath(int serverId, String productionPath){ return AgentInfoManager.getAgnetHome() + "/production/" + serverId + "/" + productionPath; } public static void checkProductionDir(int serverId){ String tagret = AgentInfoManager.getAgnetHome() + "/production/" + serverId; FilePath filePath = new FilePath(new File(tagret)); try { if(filePath.exists() == false){ filePath.mkdirs(); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } public static int getAgentMaxId(){ AgentMemoryStore agentMemoryStore = AgentMemoryStore.getInstance();
List<AgentMeta> agentMetaList = agentMemoryStore.getAgentMetaList();
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/request/ProcessKill.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/FlyFactory.java // public class FlyFactory { // // public static PeriodWork getPeriodWork(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<PeriodWork> extensionList = jenkins.getExtensionList(PeriodWork.class); // PeriodWork periodWork = extensionList.get(PeriodWork.class); // return periodWork; // } // // public static DeployInfo getDeployInfo(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<DeployInfo> extensionList = jenkins.getExtensionList(DeployInfo.class); // DeployInfo deployInfo = extensionList.get(DeployInfo.class); // return deployInfo; // } // // public static IncreaseIndexer getIncreaseIndexer(){ // return IncreaseIndexer.getInstance(); // } // // public static Map<String, Object> getPropertiesOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // // List<Item> itemList = jenkins.getAllItems(); // // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getProperties(); // } // } // } // return null; // } // // // public static NetworkSpace getNetworkSpace(){ // return NetworkSpace.getInstance(); // } // // // public static String getRootPathOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // List<Item> itemList = jenkins.getAllItems(); // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getRootDir().getAbsolutePath(); // } // } // } // return null; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/schedule/PeriodWork.java // @Extension // public class PeriodWork extends PeriodicWork { // // private RequestQueue requestQueue = new RequestQueue(); // private DeploySurveillant deploySurveillant = new DeploySurveillant(); // // public RequestQueue getRequestQueue(){ // return requestQueue; // } // // public DeploySurveillant getDeploySurveillant(){ // return deploySurveillant; // } // // public Map<String, DeployReport> getDeployReportMap(){ // return deploySurveillant.getDeployReportMap(); // } // // @Override // public long getRecurrencePeriod() { // //return MIN; // return 10000; // } // // @IgnoreJRERequirement // @Override // protected void doRun() throws Exception { // deploySurveillant.process(); // } // }
import hudson.ExtensionList; import java.util.Hashtable; import java.util.Map; import jenkins.model.Jenkins; import com.agun.flyJenkins.FlyFactory; import com.agun.flyJenkins.schedule.PeriodWork;
package com.agun.flyJenkins.request; /** * process 를 kill 하는 request 를 request queue 에 요청 한다. * * @author agun * */ public class ProcessKill implements Requester { public Object request(String host, Object arg) { int pid = (Integer) arg; Map<String, Object> argMap = new Hashtable<String, Object>(); argMap.put("host", host); argMap.put("pid", pid); RequestMap requestMap = new RequestMap(); requestMap.setType(1); requestMap.setArg(argMap); /** * request 를 queue 저장 */
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/FlyFactory.java // public class FlyFactory { // // public static PeriodWork getPeriodWork(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<PeriodWork> extensionList = jenkins.getExtensionList(PeriodWork.class); // PeriodWork periodWork = extensionList.get(PeriodWork.class); // return periodWork; // } // // public static DeployInfo getDeployInfo(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<DeployInfo> extensionList = jenkins.getExtensionList(DeployInfo.class); // DeployInfo deployInfo = extensionList.get(DeployInfo.class); // return deployInfo; // } // // public static IncreaseIndexer getIncreaseIndexer(){ // return IncreaseIndexer.getInstance(); // } // // public static Map<String, Object> getPropertiesOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // // List<Item> itemList = jenkins.getAllItems(); // // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getProperties(); // } // } // } // return null; // } // // // public static NetworkSpace getNetworkSpace(){ // return NetworkSpace.getInstance(); // } // // // public static String getRootPathOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // List<Item> itemList = jenkins.getAllItems(); // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getRootDir().getAbsolutePath(); // } // } // } // return null; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/schedule/PeriodWork.java // @Extension // public class PeriodWork extends PeriodicWork { // // private RequestQueue requestQueue = new RequestQueue(); // private DeploySurveillant deploySurveillant = new DeploySurveillant(); // // public RequestQueue getRequestQueue(){ // return requestQueue; // } // // public DeploySurveillant getDeploySurveillant(){ // return deploySurveillant; // } // // public Map<String, DeployReport> getDeployReportMap(){ // return deploySurveillant.getDeployReportMap(); // } // // @Override // public long getRecurrencePeriod() { // //return MIN; // return 10000; // } // // @IgnoreJRERequirement // @Override // protected void doRun() throws Exception { // deploySurveillant.process(); // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/ProcessKill.java import hudson.ExtensionList; import java.util.Hashtable; import java.util.Map; import jenkins.model.Jenkins; import com.agun.flyJenkins.FlyFactory; import com.agun.flyJenkins.schedule.PeriodWork; package com.agun.flyJenkins.request; /** * process 를 kill 하는 request 를 request queue 에 요청 한다. * * @author agun * */ public class ProcessKill implements Requester { public Object request(String host, Object arg) { int pid = (Integer) arg; Map<String, Object> argMap = new Hashtable<String, Object>(); argMap.put("host", host); argMap.put("pid", pid); RequestMap requestMap = new RequestMap(); requestMap.setType(1); requestMap.setArg(argMap); /** * request 를 queue 저장 */
PeriodWork periodWork = FlyFactory.getPeriodWork();
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/request/ProcessKill.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/FlyFactory.java // public class FlyFactory { // // public static PeriodWork getPeriodWork(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<PeriodWork> extensionList = jenkins.getExtensionList(PeriodWork.class); // PeriodWork periodWork = extensionList.get(PeriodWork.class); // return periodWork; // } // // public static DeployInfo getDeployInfo(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<DeployInfo> extensionList = jenkins.getExtensionList(DeployInfo.class); // DeployInfo deployInfo = extensionList.get(DeployInfo.class); // return deployInfo; // } // // public static IncreaseIndexer getIncreaseIndexer(){ // return IncreaseIndexer.getInstance(); // } // // public static Map<String, Object> getPropertiesOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // // List<Item> itemList = jenkins.getAllItems(); // // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getProperties(); // } // } // } // return null; // } // // // public static NetworkSpace getNetworkSpace(){ // return NetworkSpace.getInstance(); // } // // // public static String getRootPathOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // List<Item> itemList = jenkins.getAllItems(); // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getRootDir().getAbsolutePath(); // } // } // } // return null; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/schedule/PeriodWork.java // @Extension // public class PeriodWork extends PeriodicWork { // // private RequestQueue requestQueue = new RequestQueue(); // private DeploySurveillant deploySurveillant = new DeploySurveillant(); // // public RequestQueue getRequestQueue(){ // return requestQueue; // } // // public DeploySurveillant getDeploySurveillant(){ // return deploySurveillant; // } // // public Map<String, DeployReport> getDeployReportMap(){ // return deploySurveillant.getDeployReportMap(); // } // // @Override // public long getRecurrencePeriod() { // //return MIN; // return 10000; // } // // @IgnoreJRERequirement // @Override // protected void doRun() throws Exception { // deploySurveillant.process(); // } // }
import hudson.ExtensionList; import java.util.Hashtable; import java.util.Map; import jenkins.model.Jenkins; import com.agun.flyJenkins.FlyFactory; import com.agun.flyJenkins.schedule.PeriodWork;
package com.agun.flyJenkins.request; /** * process 를 kill 하는 request 를 request queue 에 요청 한다. * * @author agun * */ public class ProcessKill implements Requester { public Object request(String host, Object arg) { int pid = (Integer) arg; Map<String, Object> argMap = new Hashtable<String, Object>(); argMap.put("host", host); argMap.put("pid", pid); RequestMap requestMap = new RequestMap(); requestMap.setType(1); requestMap.setArg(argMap); /** * request 를 queue 저장 */
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/FlyFactory.java // public class FlyFactory { // // public static PeriodWork getPeriodWork(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<PeriodWork> extensionList = jenkins.getExtensionList(PeriodWork.class); // PeriodWork periodWork = extensionList.get(PeriodWork.class); // return periodWork; // } // // public static DeployInfo getDeployInfo(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<DeployInfo> extensionList = jenkins.getExtensionList(DeployInfo.class); // DeployInfo deployInfo = extensionList.get(DeployInfo.class); // return deployInfo; // } // // public static IncreaseIndexer getIncreaseIndexer(){ // return IncreaseIndexer.getInstance(); // } // // public static Map<String, Object> getPropertiesOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // // List<Item> itemList = jenkins.getAllItems(); // // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getProperties(); // } // } // } // return null; // } // // // public static NetworkSpace getNetworkSpace(){ // return NetworkSpace.getInstance(); // } // // // public static String getRootPathOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // List<Item> itemList = jenkins.getAllItems(); // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getRootDir().getAbsolutePath(); // } // } // } // return null; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/schedule/PeriodWork.java // @Extension // public class PeriodWork extends PeriodicWork { // // private RequestQueue requestQueue = new RequestQueue(); // private DeploySurveillant deploySurveillant = new DeploySurveillant(); // // public RequestQueue getRequestQueue(){ // return requestQueue; // } // // public DeploySurveillant getDeploySurveillant(){ // return deploySurveillant; // } // // public Map<String, DeployReport> getDeployReportMap(){ // return deploySurveillant.getDeployReportMap(); // } // // @Override // public long getRecurrencePeriod() { // //return MIN; // return 10000; // } // // @IgnoreJRERequirement // @Override // protected void doRun() throws Exception { // deploySurveillant.process(); // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/ProcessKill.java import hudson.ExtensionList; import java.util.Hashtable; import java.util.Map; import jenkins.model.Jenkins; import com.agun.flyJenkins.FlyFactory; import com.agun.flyJenkins.schedule.PeriodWork; package com.agun.flyJenkins.request; /** * process 를 kill 하는 request 를 request queue 에 요청 한다. * * @author agun * */ public class ProcessKill implements Requester { public Object request(String host, Object arg) { int pid = (Integer) arg; Map<String, Object> argMap = new Hashtable<String, Object>(); argMap.put("host", host); argMap.put("pid", pid); RequestMap requestMap = new RequestMap(); requestMap.setType(1); requestMap.setArg(argMap); /** * request 를 queue 저장 */
PeriodWork periodWork = FlyFactory.getPeriodWork();
agune/flyJenkins
common/src/main/java/org/flyJenkins/model/store/ServiceStore.java
// Path: common/src/main/java/org/flyJenkins/model/ServiceGroup.java // public class ServiceGroup { // // private int groupID; // private String name; // private Date createDate; // // private List<ServiceMeta> serviceMetaList; // // public int getGroupID() { // return groupID; // } // public void setGroupID(int groupID) { // this.groupID = groupID; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public List<ServiceMeta> getServiceMetaList() { // return serviceMetaList; // } // public void setServiceMetaList(List<ServiceMeta> serviceMetaList) { // this.serviceMetaList = serviceMetaList; // } // } // // Path: common/src/main/java/org/flyJenkins/model/ServiceMeta.java // public class ServiceMeta { // /** // * Service Server host // */ // private String host; // // // /** // * deploy destination point // */ // private String destination; // // /** // * deploy type // */ // private int type; // // /** // * Service Server Group Id // */ // private int groupID; // // /** // * Service Server Id (auto increase) // */ // private int serviceID; // /** // * test cmd after deploy // */ // private String command; // // /** // * priority of deployment // */ // private int weight; // // // /** // * test url info // */ // private String testUrl; // // private Date createDate; // // public String getHost() { // return host; // } // // // public void setHost(String host) { // this.host = host; // } // // // public String getDestination() { // return destination; // } // // // public void setDestination(String destination) { // this.destination = destination; // } // // // public int getType() { // return type; // } // // // public void setType(int type) { // this.type = type; // } // // // public int getGroupID() { // return groupID; // } // // // public void setGroupID(int groupID) { // this.groupID = groupID; // } // // // public int getServiceID() { // return serviceID; // } // // // public void setServiceID(int serviceID) { // this.serviceID = serviceID; // } // // // public String getCommand() { // return command; // } // // // public void setCommand(String command) { // this.command = command; // } // // // public int getWeight() { // return weight; // } // // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getTestUrl() { // return testUrl; // } // // // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.flyJenkins.model.ServiceGroup; import org.flyJenkins.model.ServiceMeta;
package org.flyJenkins.model.store; public class ServiceStore { Map<Integer, ServiceMeta> serviceMap;
// Path: common/src/main/java/org/flyJenkins/model/ServiceGroup.java // public class ServiceGroup { // // private int groupID; // private String name; // private Date createDate; // // private List<ServiceMeta> serviceMetaList; // // public int getGroupID() { // return groupID; // } // public void setGroupID(int groupID) { // this.groupID = groupID; // } // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public List<ServiceMeta> getServiceMetaList() { // return serviceMetaList; // } // public void setServiceMetaList(List<ServiceMeta> serviceMetaList) { // this.serviceMetaList = serviceMetaList; // } // } // // Path: common/src/main/java/org/flyJenkins/model/ServiceMeta.java // public class ServiceMeta { // /** // * Service Server host // */ // private String host; // // // /** // * deploy destination point // */ // private String destination; // // /** // * deploy type // */ // private int type; // // /** // * Service Server Group Id // */ // private int groupID; // // /** // * Service Server Id (auto increase) // */ // private int serviceID; // /** // * test cmd after deploy // */ // private String command; // // /** // * priority of deployment // */ // private int weight; // // // /** // * test url info // */ // private String testUrl; // // private Date createDate; // // public String getHost() { // return host; // } // // // public void setHost(String host) { // this.host = host; // } // // // public String getDestination() { // return destination; // } // // // public void setDestination(String destination) { // this.destination = destination; // } // // // public int getType() { // return type; // } // // // public void setType(int type) { // this.type = type; // } // // // public int getGroupID() { // return groupID; // } // // // public void setGroupID(int groupID) { // this.groupID = groupID; // } // // // public int getServiceID() { // return serviceID; // } // // // public void setServiceID(int serviceID) { // this.serviceID = serviceID; // } // // // public String getCommand() { // return command; // } // // // public void setCommand(String command) { // this.command = command; // } // // // public int getWeight() { // return weight; // } // // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getTestUrl() { // return testUrl; // } // // // public void setTestUrl(String testUrl) { // this.testUrl = testUrl; // } // // // public long getCreateDate() { // if(createDate == null) return 0L; // return createDate.getTime(); // } // // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // } // Path: common/src/main/java/org/flyJenkins/model/store/ServiceStore.java import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.flyJenkins.model.ServiceGroup; import org.flyJenkins.model.ServiceMeta; package org.flyJenkins.model.store; public class ServiceStore { Map<Integer, ServiceMeta> serviceMap;
Map<Integer, ServiceGroup> groupMap;
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/persistence/DeployLogSaveable.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/DeployLog.java // public class DeployLog { // // private String deployId; // private String jobName; // private String production; // private String host; // private int serviceGroupId; // private int serviceId; // private Date date; // private Date reserveDate; // private int requestOrder = 0; // // public int getRequestOrder() { // return requestOrder; // } // // public void setRequestOrder(int requestOrder) { // this.requestOrder = requestOrder; // } // // public String getDeployId() { // return deployId; // } // // public void setDeployId(String deployId) { // this.deployId = deployId; // } // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public String getProduction() { // return production; // } // // public void setProduction(String production) { // this.production = production; // } // // public Date getReserveDate() { // return reserveDate; // } // // public void setReserveDate(Date reserveDate) { // this.reserveDate = reserveDate; // } // // public int getServiceGroupId() { // return serviceGroupId; // } // // public void setServiceGroupId(int serviceGroupId) { // this.serviceGroupId = serviceGroupId; // } // // public int getServiceId() { // return serviceId; // } // // public void setServiceId(int serviceId) { // this.serviceId = serviceId; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/util/ModelSoting.java // public class ModelSoting { // public static void serviceSortByWeight(List<ServiceMeta> serviceMetaList){ // // Comparator<ServiceMeta> comparator = new Comparator<ServiceMeta>() { // public int compare(ServiceMeta o1, ServiceMeta o2) { // return (o1.getWeight() > o2.getWeight())? 1 : -1 ; // } // // }; // Collections.sort(serviceMetaList, comparator); // } // // public static void productionSortDate(List<ProductionMeta> productionList){ // Comparator<ProductionMeta> comparator = new Comparator<ProductionMeta>() { // public int compare(ProductionMeta o1, ProductionMeta o2) { // return (o1.getCreateDate().getTime() < o2.getCreateDate().getTime())? 1 : -1 ; // } // }; // // Collections.sort(productionList, comparator); // // } // // // public static void deployRequestSortDate(List<DeployRequest> deployRequestList){ // Comparator<DeployRequest> comparator = new Comparator<DeployRequest>() { // public int compare(DeployRequest o1, DeployRequest o2) { // return (o1.getDate().getTime() < o2.getDate().getTime())? 1 : -1 ; // } // }; // Collections.sort(deployRequestList, comparator); // } // // public static void deployLogSortDate(List<DeployLog> deployLogList){ // Comparator<DeployLog> comparator = new Comparator<DeployLog>() { // public int compare(DeployLog o1, DeployLog o2) { // return (o1.getDate().getTime() < o2.getDate().getTime())? 1 : -1 ; // } // }; // Collections.sort(deployLogList, comparator); // } // // public static void deployReportSortId(List<DeployReport> deployReportList){ // Comparator<DeployReport> comparator = new Comparator<DeployReport>() { // public int compare(DeployReport o1, DeployReport o2) { // return o2.getDeployId().compareTo(o1.getDeployId()); // } // }; // Collections.sort(deployReportList, comparator); // } // }
import java.io.File; import java.io.IOException; import java.util.List; import jenkins.model.Jenkins; import com.agun.flyJenkins.model.DeployLog; import com.agun.flyJenkins.model.util.ModelSoting; import hudson.BulkChange; import hudson.XmlFile; import hudson.model.Saveable; import hudson.model.listeners.SaveableListener;
package com.agun.flyJenkins.persistence; public class DeployLogSaveable implements Saveable{ private List<DeployLog> deployLogList = null; public void save() throws IOException { if(deployLogList != null){
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/DeployLog.java // public class DeployLog { // // private String deployId; // private String jobName; // private String production; // private String host; // private int serviceGroupId; // private int serviceId; // private Date date; // private Date reserveDate; // private int requestOrder = 0; // // public int getRequestOrder() { // return requestOrder; // } // // public void setRequestOrder(int requestOrder) { // this.requestOrder = requestOrder; // } // // public String getDeployId() { // return deployId; // } // // public void setDeployId(String deployId) { // this.deployId = deployId; // } // // public String getJobName() { // return jobName; // } // // public void setJobName(String jobName) { // this.jobName = jobName; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public String getProduction() { // return production; // } // // public void setProduction(String production) { // this.production = production; // } // // public Date getReserveDate() { // return reserveDate; // } // // public void setReserveDate(Date reserveDate) { // this.reserveDate = reserveDate; // } // // public int getServiceGroupId() { // return serviceGroupId; // } // // public void setServiceGroupId(int serviceGroupId) { // this.serviceGroupId = serviceGroupId; // } // // public int getServiceId() { // return serviceId; // } // // public void setServiceId(int serviceId) { // this.serviceId = serviceId; // } // // public String getHost() { // return host; // } // // public void setHost(String host) { // this.host = host; // } // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/model/util/ModelSoting.java // public class ModelSoting { // public static void serviceSortByWeight(List<ServiceMeta> serviceMetaList){ // // Comparator<ServiceMeta> comparator = new Comparator<ServiceMeta>() { // public int compare(ServiceMeta o1, ServiceMeta o2) { // return (o1.getWeight() > o2.getWeight())? 1 : -1 ; // } // // }; // Collections.sort(serviceMetaList, comparator); // } // // public static void productionSortDate(List<ProductionMeta> productionList){ // Comparator<ProductionMeta> comparator = new Comparator<ProductionMeta>() { // public int compare(ProductionMeta o1, ProductionMeta o2) { // return (o1.getCreateDate().getTime() < o2.getCreateDate().getTime())? 1 : -1 ; // } // }; // // Collections.sort(productionList, comparator); // // } // // // public static void deployRequestSortDate(List<DeployRequest> deployRequestList){ // Comparator<DeployRequest> comparator = new Comparator<DeployRequest>() { // public int compare(DeployRequest o1, DeployRequest o2) { // return (o1.getDate().getTime() < o2.getDate().getTime())? 1 : -1 ; // } // }; // Collections.sort(deployRequestList, comparator); // } // // public static void deployLogSortDate(List<DeployLog> deployLogList){ // Comparator<DeployLog> comparator = new Comparator<DeployLog>() { // public int compare(DeployLog o1, DeployLog o2) { // return (o1.getDate().getTime() < o2.getDate().getTime())? 1 : -1 ; // } // }; // Collections.sort(deployLogList, comparator); // } // // public static void deployReportSortId(List<DeployReport> deployReportList){ // Comparator<DeployReport> comparator = new Comparator<DeployReport>() { // public int compare(DeployReport o1, DeployReport o2) { // return o2.getDeployId().compareTo(o1.getDeployId()); // } // }; // Collections.sort(deployReportList, comparator); // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/persistence/DeployLogSaveable.java import java.io.File; import java.io.IOException; import java.util.List; import jenkins.model.Jenkins; import com.agun.flyJenkins.model.DeployLog; import com.agun.flyJenkins.model.util.ModelSoting; import hudson.BulkChange; import hudson.XmlFile; import hudson.model.Saveable; import hudson.model.listeners.SaveableListener; package com.agun.flyJenkins.persistence; public class DeployLogSaveable implements Saveable{ private List<DeployLog> deployLogList = null; public void save() throws IOException { if(deployLogList != null){
ModelSoting.deployLogSortDate(deployLogList);
agune/flyJenkins
flyJenkins/src/main/java/org/flyJenkins/action/FlyRootAction.java
// Path: flyJenkins/src/main/java/org/flyJenkins/boot/FlyBootstrap.java // public class FlyBootstrap { // // public static void start(){ // //TODO make initial network space // // //TODO make memory store // // //TODO make resource director // } // }
import hudson.Extension; import hudson.model.RootAction; import org.flyJenkins.boot.FlyBootstrap;
/** * This class is root of flyJenkins. * @author agun * */ package org.flyJenkins.action; @Extension public class FlyRootAction implements RootAction { /** * flyJenkins does booting. */ public FlyRootAction(){ System.out.println("====> new flyRootAction");
// Path: flyJenkins/src/main/java/org/flyJenkins/boot/FlyBootstrap.java // public class FlyBootstrap { // // public static void start(){ // //TODO make initial network space // // //TODO make memory store // // //TODO make resource director // } // } // Path: flyJenkins/src/main/java/org/flyJenkins/action/FlyRootAction.java import hudson.Extension; import hudson.model.RootAction; import org.flyJenkins.boot.FlyBootstrap; /** * This class is root of flyJenkins. * @author agun * */ package org.flyJenkins.action; @Extension public class FlyRootAction implements RootAction { /** * flyJenkins does booting. */ public FlyRootAction(){ System.out.println("====> new flyRootAction");
FlyBootstrap.start();
agune/flyJenkins
flyJenkins/src/main/java/org/flyJenkins/component/persistent/PersistentTemplate.java
// Path: flyJenkins/src/main/java/org/flyJenkins/component/persistent/hsql/HSQLDriver.java // public class HSQLDriver implements PersistentDriver { // // Connection conn = null; // Statement st = null; // // @Override // public void initDevice() { // try { // Class.forName("org.hsqldb.jdbcDriver"); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } // try { // conn = DriverManager.getConnection("jdbc:hsqldb:file:testdb", "sa", ""); // st = conn.createStatement(); // statements // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public void initSchema() { // int i; // try { // i = st.executeUpdate("CREATE TABLE productions ( id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL, job_id INTEGER, job_name VARCHAR(255), build INTEGER, output VARCHAR(255), create_at TIMESTAMP DEFAULT now() )"); // if (i == -1) { // System.out.println("db error : can't create table productions " ); // } // // i = st.executeUpdate("CREATE TABLE serviceGroups ( id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL, group_name VARCHAR(255), create_at TIMESTAMP DEFAULT now() )"); // if (i == -1) { // System.out.println("db error : can't create table serviceGroups " ); // } // // i = st.executeUpdate("CREATE TABLE serviceMetas ( id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL, group_id INTEGER, host VARCHAR(255), destination VARCHAR(255), service_type INTEGER, command VARCHAR(255), weight INTEGER, service_name VARCHAR(255), test_url VARCHAR(255), create_at TIMESTAMP DEFAULT now() )"); // if (i == -1) { // System.out.println("db error : can't create table serviceMetas " ); // } // // } catch (SQLException e) { // e.printStackTrace(); // } // // } // // public Connection getConn() { // return conn; // } // // public Statement getStatement() { // try { // return conn.createStatement(); // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // }
import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.flyJenkins.component.persistent.hsql.HSQLDriver;
public static PersistentTemplate getInstance(String driverClassName){ if(driverClassName == null) return instance; if(instance == null) instance = new PersistentTemplate(driverClassName); instance.setDriverClassName(driverClassName); instance.getPersistentDriver(); return instance; } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } /*** * obtain persistent driver instance by class name * @return PersistentDriver or null */ public PersistentDriver getPersistentDriver(){ if(driverClassName == null || driverClassName.length() == 0) return null; if(pDriver == null){ try {
// Path: flyJenkins/src/main/java/org/flyJenkins/component/persistent/hsql/HSQLDriver.java // public class HSQLDriver implements PersistentDriver { // // Connection conn = null; // Statement st = null; // // @Override // public void initDevice() { // try { // Class.forName("org.hsqldb.jdbcDriver"); // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } // try { // conn = DriverManager.getConnection("jdbc:hsqldb:file:testdb", "sa", ""); // st = conn.createStatement(); // statements // } catch (SQLException e) { // e.printStackTrace(); // } // } // // public void initSchema() { // int i; // try { // i = st.executeUpdate("CREATE TABLE productions ( id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL, job_id INTEGER, job_name VARCHAR(255), build INTEGER, output VARCHAR(255), create_at TIMESTAMP DEFAULT now() )"); // if (i == -1) { // System.out.println("db error : can't create table productions " ); // } // // i = st.executeUpdate("CREATE TABLE serviceGroups ( id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL, group_name VARCHAR(255), create_at TIMESTAMP DEFAULT now() )"); // if (i == -1) { // System.out.println("db error : can't create table serviceGroups " ); // } // // i = st.executeUpdate("CREATE TABLE serviceMetas ( id INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL, group_id INTEGER, host VARCHAR(255), destination VARCHAR(255), service_type INTEGER, command VARCHAR(255), weight INTEGER, service_name VARCHAR(255), test_url VARCHAR(255), create_at TIMESTAMP DEFAULT now() )"); // if (i == -1) { // System.out.println("db error : can't create table serviceMetas " ); // } // // } catch (SQLException e) { // e.printStackTrace(); // } // // } // // public Connection getConn() { // return conn; // } // // public Statement getStatement() { // try { // return conn.createStatement(); // } catch (SQLException e) { // e.printStackTrace(); // } // return null; // } // // } // Path: flyJenkins/src/main/java/org/flyJenkins/component/persistent/PersistentTemplate.java import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.flyJenkins.component.persistent.hsql.HSQLDriver; public static PersistentTemplate getInstance(String driverClassName){ if(driverClassName == null) return instance; if(instance == null) instance = new PersistentTemplate(driverClassName); instance.setDriverClassName(driverClassName); instance.getPersistentDriver(); return instance; } public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } /*** * obtain persistent driver instance by class name * @return PersistentDriver or null */ public PersistentDriver getPersistentDriver(){ if(driverClassName == null || driverClassName.length() == 0) return null; if(pDriver == null){ try {
pDriver =(HSQLDriver) Class.forName(driverClassName).newInstance();
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/process/FlyRequester.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/FlyFactory.java // public class FlyFactory { // // public static PeriodWork getPeriodWork(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<PeriodWork> extensionList = jenkins.getExtensionList(PeriodWork.class); // PeriodWork periodWork = extensionList.get(PeriodWork.class); // return periodWork; // } // // public static DeployInfo getDeployInfo(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<DeployInfo> extensionList = jenkins.getExtensionList(DeployInfo.class); // DeployInfo deployInfo = extensionList.get(DeployInfo.class); // return deployInfo; // } // // public static IncreaseIndexer getIncreaseIndexer(){ // return IncreaseIndexer.getInstance(); // } // // public static Map<String, Object> getPropertiesOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // // List<Item> itemList = jenkins.getAllItems(); // // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getProperties(); // } // } // } // return null; // } // // // public static NetworkSpace getNetworkSpace(){ // return NetworkSpace.getInstance(); // } // // // public static String getRootPathOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // List<Item> itemList = jenkins.getAllItems(); // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getRootDir().getAbsolutePath(); // } // } // } // return null; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestMap.java // public class RequestMap { // int type; // Object arg; // // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public Object getArg() { // return arg; // } // public void setArg(Object arg) { // this.arg = arg; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestQueue.java // public class RequestQueue { // // private Map<String, LinkedList<RequestMap>> requestQueueMap = new Hashtable<String, LinkedList<RequestMap>>(); // // public LinkedList<RequestMap> getRequest(String host){ // if(requestQueueMap.containsKey(host)){ // return requestQueueMap.get(host); // } // return null; // } // // // public void add(String host, RequestMap requestMap){ // if(requestQueueMap.containsKey(host)){ // requestQueueMap.get(host).add(requestMap); // }else{ // LinkedList<RequestMap> requestQueue = new LinkedList<RequestMap>(); // requestQueue.add(requestMap); // requestQueueMap.put(host, requestQueue); // } // } // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/schedule/PeriodWork.java // @Extension // public class PeriodWork extends PeriodicWork { // // private RequestQueue requestQueue = new RequestQueue(); // private DeploySurveillant deploySurveillant = new DeploySurveillant(); // // public RequestQueue getRequestQueue(){ // return requestQueue; // } // // public DeploySurveillant getDeploySurveillant(){ // return deploySurveillant; // } // // public Map<String, DeployReport> getDeployReportMap(){ // return deploySurveillant.getDeployReportMap(); // } // // @Override // public long getRecurrencePeriod() { // //return MIN; // return 10000; // } // // @IgnoreJRERequirement // @Override // protected void doRun() throws Exception { // deploySurveillant.process(); // } // }
import java.util.Collections; import java.util.Hashtable; import java.util.LinkedList; import java.util.Map; import com.agun.flyJenkins.FlyFactory; import com.agun.flyJenkins.request.RequestMap; import com.agun.flyJenkins.request.RequestQueue; import com.agun.flyJenkins.schedule.PeriodWork;
package com.agun.flyJenkins.process; public class FlyRequester implements FlyProcess { private static FlyRequester flyRequester = new FlyRequester(); private FlyRequester(){ } public static FlyRequester getInstance(){ return FlyRequester.flyRequester; } private Map<String, Object> peekRequest(String host){
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/FlyFactory.java // public class FlyFactory { // // public static PeriodWork getPeriodWork(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<PeriodWork> extensionList = jenkins.getExtensionList(PeriodWork.class); // PeriodWork periodWork = extensionList.get(PeriodWork.class); // return periodWork; // } // // public static DeployInfo getDeployInfo(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<DeployInfo> extensionList = jenkins.getExtensionList(DeployInfo.class); // DeployInfo deployInfo = extensionList.get(DeployInfo.class); // return deployInfo; // } // // public static IncreaseIndexer getIncreaseIndexer(){ // return IncreaseIndexer.getInstance(); // } // // public static Map<String, Object> getPropertiesOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // // List<Item> itemList = jenkins.getAllItems(); // // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getProperties(); // } // } // } // return null; // } // // // public static NetworkSpace getNetworkSpace(){ // return NetworkSpace.getInstance(); // } // // // public static String getRootPathOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // List<Item> itemList = jenkins.getAllItems(); // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getRootDir().getAbsolutePath(); // } // } // } // return null; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestMap.java // public class RequestMap { // int type; // Object arg; // // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public Object getArg() { // return arg; // } // public void setArg(Object arg) { // this.arg = arg; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestQueue.java // public class RequestQueue { // // private Map<String, LinkedList<RequestMap>> requestQueueMap = new Hashtable<String, LinkedList<RequestMap>>(); // // public LinkedList<RequestMap> getRequest(String host){ // if(requestQueueMap.containsKey(host)){ // return requestQueueMap.get(host); // } // return null; // } // // // public void add(String host, RequestMap requestMap){ // if(requestQueueMap.containsKey(host)){ // requestQueueMap.get(host).add(requestMap); // }else{ // LinkedList<RequestMap> requestQueue = new LinkedList<RequestMap>(); // requestQueue.add(requestMap); // requestQueueMap.put(host, requestQueue); // } // } // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/schedule/PeriodWork.java // @Extension // public class PeriodWork extends PeriodicWork { // // private RequestQueue requestQueue = new RequestQueue(); // private DeploySurveillant deploySurveillant = new DeploySurveillant(); // // public RequestQueue getRequestQueue(){ // return requestQueue; // } // // public DeploySurveillant getDeploySurveillant(){ // return deploySurveillant; // } // // public Map<String, DeployReport> getDeployReportMap(){ // return deploySurveillant.getDeployReportMap(); // } // // @Override // public long getRecurrencePeriod() { // //return MIN; // return 10000; // } // // @IgnoreJRERequirement // @Override // protected void doRun() throws Exception { // deploySurveillant.process(); // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/process/FlyRequester.java import java.util.Collections; import java.util.Hashtable; import java.util.LinkedList; import java.util.Map; import com.agun.flyJenkins.FlyFactory; import com.agun.flyJenkins.request.RequestMap; import com.agun.flyJenkins.request.RequestQueue; import com.agun.flyJenkins.schedule.PeriodWork; package com.agun.flyJenkins.process; public class FlyRequester implements FlyProcess { private static FlyRequester flyRequester = new FlyRequester(); private FlyRequester(){ } public static FlyRequester getInstance(){ return FlyRequester.flyRequester; } private Map<String, Object> peekRequest(String host){
PeriodWork periodWork = FlyFactory.getPeriodWork();
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/process/FlyRequester.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/FlyFactory.java // public class FlyFactory { // // public static PeriodWork getPeriodWork(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<PeriodWork> extensionList = jenkins.getExtensionList(PeriodWork.class); // PeriodWork periodWork = extensionList.get(PeriodWork.class); // return periodWork; // } // // public static DeployInfo getDeployInfo(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<DeployInfo> extensionList = jenkins.getExtensionList(DeployInfo.class); // DeployInfo deployInfo = extensionList.get(DeployInfo.class); // return deployInfo; // } // // public static IncreaseIndexer getIncreaseIndexer(){ // return IncreaseIndexer.getInstance(); // } // // public static Map<String, Object> getPropertiesOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // // List<Item> itemList = jenkins.getAllItems(); // // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getProperties(); // } // } // } // return null; // } // // // public static NetworkSpace getNetworkSpace(){ // return NetworkSpace.getInstance(); // } // // // public static String getRootPathOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // List<Item> itemList = jenkins.getAllItems(); // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getRootDir().getAbsolutePath(); // } // } // } // return null; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestMap.java // public class RequestMap { // int type; // Object arg; // // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public Object getArg() { // return arg; // } // public void setArg(Object arg) { // this.arg = arg; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestQueue.java // public class RequestQueue { // // private Map<String, LinkedList<RequestMap>> requestQueueMap = new Hashtable<String, LinkedList<RequestMap>>(); // // public LinkedList<RequestMap> getRequest(String host){ // if(requestQueueMap.containsKey(host)){ // return requestQueueMap.get(host); // } // return null; // } // // // public void add(String host, RequestMap requestMap){ // if(requestQueueMap.containsKey(host)){ // requestQueueMap.get(host).add(requestMap); // }else{ // LinkedList<RequestMap> requestQueue = new LinkedList<RequestMap>(); // requestQueue.add(requestMap); // requestQueueMap.put(host, requestQueue); // } // } // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/schedule/PeriodWork.java // @Extension // public class PeriodWork extends PeriodicWork { // // private RequestQueue requestQueue = new RequestQueue(); // private DeploySurveillant deploySurveillant = new DeploySurveillant(); // // public RequestQueue getRequestQueue(){ // return requestQueue; // } // // public DeploySurveillant getDeploySurveillant(){ // return deploySurveillant; // } // // public Map<String, DeployReport> getDeployReportMap(){ // return deploySurveillant.getDeployReportMap(); // } // // @Override // public long getRecurrencePeriod() { // //return MIN; // return 10000; // } // // @IgnoreJRERequirement // @Override // protected void doRun() throws Exception { // deploySurveillant.process(); // } // }
import java.util.Collections; import java.util.Hashtable; import java.util.LinkedList; import java.util.Map; import com.agun.flyJenkins.FlyFactory; import com.agun.flyJenkins.request.RequestMap; import com.agun.flyJenkins.request.RequestQueue; import com.agun.flyJenkins.schedule.PeriodWork;
package com.agun.flyJenkins.process; public class FlyRequester implements FlyProcess { private static FlyRequester flyRequester = new FlyRequester(); private FlyRequester(){ } public static FlyRequester getInstance(){ return FlyRequester.flyRequester; } private Map<String, Object> peekRequest(String host){
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/FlyFactory.java // public class FlyFactory { // // public static PeriodWork getPeriodWork(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<PeriodWork> extensionList = jenkins.getExtensionList(PeriodWork.class); // PeriodWork periodWork = extensionList.get(PeriodWork.class); // return periodWork; // } // // public static DeployInfo getDeployInfo(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<DeployInfo> extensionList = jenkins.getExtensionList(DeployInfo.class); // DeployInfo deployInfo = extensionList.get(DeployInfo.class); // return deployInfo; // } // // public static IncreaseIndexer getIncreaseIndexer(){ // return IncreaseIndexer.getInstance(); // } // // public static Map<String, Object> getPropertiesOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // // List<Item> itemList = jenkins.getAllItems(); // // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getProperties(); // } // } // } // return null; // } // // // public static NetworkSpace getNetworkSpace(){ // return NetworkSpace.getInstance(); // } // // // public static String getRootPathOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // List<Item> itemList = jenkins.getAllItems(); // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getRootDir().getAbsolutePath(); // } // } // } // return null; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestMap.java // public class RequestMap { // int type; // Object arg; // // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public Object getArg() { // return arg; // } // public void setArg(Object arg) { // this.arg = arg; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestQueue.java // public class RequestQueue { // // private Map<String, LinkedList<RequestMap>> requestQueueMap = new Hashtable<String, LinkedList<RequestMap>>(); // // public LinkedList<RequestMap> getRequest(String host){ // if(requestQueueMap.containsKey(host)){ // return requestQueueMap.get(host); // } // return null; // } // // // public void add(String host, RequestMap requestMap){ // if(requestQueueMap.containsKey(host)){ // requestQueueMap.get(host).add(requestMap); // }else{ // LinkedList<RequestMap> requestQueue = new LinkedList<RequestMap>(); // requestQueue.add(requestMap); // requestQueueMap.put(host, requestQueue); // } // } // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/schedule/PeriodWork.java // @Extension // public class PeriodWork extends PeriodicWork { // // private RequestQueue requestQueue = new RequestQueue(); // private DeploySurveillant deploySurveillant = new DeploySurveillant(); // // public RequestQueue getRequestQueue(){ // return requestQueue; // } // // public DeploySurveillant getDeploySurveillant(){ // return deploySurveillant; // } // // public Map<String, DeployReport> getDeployReportMap(){ // return deploySurveillant.getDeployReportMap(); // } // // @Override // public long getRecurrencePeriod() { // //return MIN; // return 10000; // } // // @IgnoreJRERequirement // @Override // protected void doRun() throws Exception { // deploySurveillant.process(); // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/process/FlyRequester.java import java.util.Collections; import java.util.Hashtable; import java.util.LinkedList; import java.util.Map; import com.agun.flyJenkins.FlyFactory; import com.agun.flyJenkins.request.RequestMap; import com.agun.flyJenkins.request.RequestQueue; import com.agun.flyJenkins.schedule.PeriodWork; package com.agun.flyJenkins.process; public class FlyRequester implements FlyProcess { private static FlyRequester flyRequester = new FlyRequester(); private FlyRequester(){ } public static FlyRequester getInstance(){ return FlyRequester.flyRequester; } private Map<String, Object> peekRequest(String host){
PeriodWork periodWork = FlyFactory.getPeriodWork();
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/process/FlyRequester.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/FlyFactory.java // public class FlyFactory { // // public static PeriodWork getPeriodWork(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<PeriodWork> extensionList = jenkins.getExtensionList(PeriodWork.class); // PeriodWork periodWork = extensionList.get(PeriodWork.class); // return periodWork; // } // // public static DeployInfo getDeployInfo(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<DeployInfo> extensionList = jenkins.getExtensionList(DeployInfo.class); // DeployInfo deployInfo = extensionList.get(DeployInfo.class); // return deployInfo; // } // // public static IncreaseIndexer getIncreaseIndexer(){ // return IncreaseIndexer.getInstance(); // } // // public static Map<String, Object> getPropertiesOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // // List<Item> itemList = jenkins.getAllItems(); // // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getProperties(); // } // } // } // return null; // } // // // public static NetworkSpace getNetworkSpace(){ // return NetworkSpace.getInstance(); // } // // // public static String getRootPathOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // List<Item> itemList = jenkins.getAllItems(); // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getRootDir().getAbsolutePath(); // } // } // } // return null; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestMap.java // public class RequestMap { // int type; // Object arg; // // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public Object getArg() { // return arg; // } // public void setArg(Object arg) { // this.arg = arg; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestQueue.java // public class RequestQueue { // // private Map<String, LinkedList<RequestMap>> requestQueueMap = new Hashtable<String, LinkedList<RequestMap>>(); // // public LinkedList<RequestMap> getRequest(String host){ // if(requestQueueMap.containsKey(host)){ // return requestQueueMap.get(host); // } // return null; // } // // // public void add(String host, RequestMap requestMap){ // if(requestQueueMap.containsKey(host)){ // requestQueueMap.get(host).add(requestMap); // }else{ // LinkedList<RequestMap> requestQueue = new LinkedList<RequestMap>(); // requestQueue.add(requestMap); // requestQueueMap.put(host, requestQueue); // } // } // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/schedule/PeriodWork.java // @Extension // public class PeriodWork extends PeriodicWork { // // private RequestQueue requestQueue = new RequestQueue(); // private DeploySurveillant deploySurveillant = new DeploySurveillant(); // // public RequestQueue getRequestQueue(){ // return requestQueue; // } // // public DeploySurveillant getDeploySurveillant(){ // return deploySurveillant; // } // // public Map<String, DeployReport> getDeployReportMap(){ // return deploySurveillant.getDeployReportMap(); // } // // @Override // public long getRecurrencePeriod() { // //return MIN; // return 10000; // } // // @IgnoreJRERequirement // @Override // protected void doRun() throws Exception { // deploySurveillant.process(); // } // }
import java.util.Collections; import java.util.Hashtable; import java.util.LinkedList; import java.util.Map; import com.agun.flyJenkins.FlyFactory; import com.agun.flyJenkins.request.RequestMap; import com.agun.flyJenkins.request.RequestQueue; import com.agun.flyJenkins.schedule.PeriodWork;
package com.agun.flyJenkins.process; public class FlyRequester implements FlyProcess { private static FlyRequester flyRequester = new FlyRequester(); private FlyRequester(){ } public static FlyRequester getInstance(){ return FlyRequester.flyRequester; } private Map<String, Object> peekRequest(String host){ PeriodWork periodWork = FlyFactory.getPeriodWork();
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/FlyFactory.java // public class FlyFactory { // // public static PeriodWork getPeriodWork(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<PeriodWork> extensionList = jenkins.getExtensionList(PeriodWork.class); // PeriodWork periodWork = extensionList.get(PeriodWork.class); // return periodWork; // } // // public static DeployInfo getDeployInfo(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<DeployInfo> extensionList = jenkins.getExtensionList(DeployInfo.class); // DeployInfo deployInfo = extensionList.get(DeployInfo.class); // return deployInfo; // } // // public static IncreaseIndexer getIncreaseIndexer(){ // return IncreaseIndexer.getInstance(); // } // // public static Map<String, Object> getPropertiesOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // // List<Item> itemList = jenkins.getAllItems(); // // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getProperties(); // } // } // } // return null; // } // // // public static NetworkSpace getNetworkSpace(){ // return NetworkSpace.getInstance(); // } // // // public static String getRootPathOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // List<Item> itemList = jenkins.getAllItems(); // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getRootDir().getAbsolutePath(); // } // } // } // return null; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestMap.java // public class RequestMap { // int type; // Object arg; // // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public Object getArg() { // return arg; // } // public void setArg(Object arg) { // this.arg = arg; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestQueue.java // public class RequestQueue { // // private Map<String, LinkedList<RequestMap>> requestQueueMap = new Hashtable<String, LinkedList<RequestMap>>(); // // public LinkedList<RequestMap> getRequest(String host){ // if(requestQueueMap.containsKey(host)){ // return requestQueueMap.get(host); // } // return null; // } // // // public void add(String host, RequestMap requestMap){ // if(requestQueueMap.containsKey(host)){ // requestQueueMap.get(host).add(requestMap); // }else{ // LinkedList<RequestMap> requestQueue = new LinkedList<RequestMap>(); // requestQueue.add(requestMap); // requestQueueMap.put(host, requestQueue); // } // } // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/schedule/PeriodWork.java // @Extension // public class PeriodWork extends PeriodicWork { // // private RequestQueue requestQueue = new RequestQueue(); // private DeploySurveillant deploySurveillant = new DeploySurveillant(); // // public RequestQueue getRequestQueue(){ // return requestQueue; // } // // public DeploySurveillant getDeploySurveillant(){ // return deploySurveillant; // } // // public Map<String, DeployReport> getDeployReportMap(){ // return deploySurveillant.getDeployReportMap(); // } // // @Override // public long getRecurrencePeriod() { // //return MIN; // return 10000; // } // // @IgnoreJRERequirement // @Override // protected void doRun() throws Exception { // deploySurveillant.process(); // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/process/FlyRequester.java import java.util.Collections; import java.util.Hashtable; import java.util.LinkedList; import java.util.Map; import com.agun.flyJenkins.FlyFactory; import com.agun.flyJenkins.request.RequestMap; import com.agun.flyJenkins.request.RequestQueue; import com.agun.flyJenkins.schedule.PeriodWork; package com.agun.flyJenkins.process; public class FlyRequester implements FlyProcess { private static FlyRequester flyRequester = new FlyRequester(); private FlyRequester(){ } public static FlyRequester getInstance(){ return FlyRequester.flyRequester; } private Map<String, Object> peekRequest(String host){ PeriodWork periodWork = FlyFactory.getPeriodWork();
RequestQueue requestQueue = periodWork.getRequestQueue();
agune/flyJenkins
flyJenkins/src/main/java/com/agun/flyJenkins/process/FlyRequester.java
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/FlyFactory.java // public class FlyFactory { // // public static PeriodWork getPeriodWork(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<PeriodWork> extensionList = jenkins.getExtensionList(PeriodWork.class); // PeriodWork periodWork = extensionList.get(PeriodWork.class); // return periodWork; // } // // public static DeployInfo getDeployInfo(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<DeployInfo> extensionList = jenkins.getExtensionList(DeployInfo.class); // DeployInfo deployInfo = extensionList.get(DeployInfo.class); // return deployInfo; // } // // public static IncreaseIndexer getIncreaseIndexer(){ // return IncreaseIndexer.getInstance(); // } // // public static Map<String, Object> getPropertiesOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // // List<Item> itemList = jenkins.getAllItems(); // // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getProperties(); // } // } // } // return null; // } // // // public static NetworkSpace getNetworkSpace(){ // return NetworkSpace.getInstance(); // } // // // public static String getRootPathOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // List<Item> itemList = jenkins.getAllItems(); // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getRootDir().getAbsolutePath(); // } // } // } // return null; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestMap.java // public class RequestMap { // int type; // Object arg; // // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public Object getArg() { // return arg; // } // public void setArg(Object arg) { // this.arg = arg; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestQueue.java // public class RequestQueue { // // private Map<String, LinkedList<RequestMap>> requestQueueMap = new Hashtable<String, LinkedList<RequestMap>>(); // // public LinkedList<RequestMap> getRequest(String host){ // if(requestQueueMap.containsKey(host)){ // return requestQueueMap.get(host); // } // return null; // } // // // public void add(String host, RequestMap requestMap){ // if(requestQueueMap.containsKey(host)){ // requestQueueMap.get(host).add(requestMap); // }else{ // LinkedList<RequestMap> requestQueue = new LinkedList<RequestMap>(); // requestQueue.add(requestMap); // requestQueueMap.put(host, requestQueue); // } // } // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/schedule/PeriodWork.java // @Extension // public class PeriodWork extends PeriodicWork { // // private RequestQueue requestQueue = new RequestQueue(); // private DeploySurveillant deploySurveillant = new DeploySurveillant(); // // public RequestQueue getRequestQueue(){ // return requestQueue; // } // // public DeploySurveillant getDeploySurveillant(){ // return deploySurveillant; // } // // public Map<String, DeployReport> getDeployReportMap(){ // return deploySurveillant.getDeployReportMap(); // } // // @Override // public long getRecurrencePeriod() { // //return MIN; // return 10000; // } // // @IgnoreJRERequirement // @Override // protected void doRun() throws Exception { // deploySurveillant.process(); // } // }
import java.util.Collections; import java.util.Hashtable; import java.util.LinkedList; import java.util.Map; import com.agun.flyJenkins.FlyFactory; import com.agun.flyJenkins.request.RequestMap; import com.agun.flyJenkins.request.RequestQueue; import com.agun.flyJenkins.schedule.PeriodWork;
package com.agun.flyJenkins.process; public class FlyRequester implements FlyProcess { private static FlyRequester flyRequester = new FlyRequester(); private FlyRequester(){ } public static FlyRequester getInstance(){ return FlyRequester.flyRequester; } private Map<String, Object> peekRequest(String host){ PeriodWork periodWork = FlyFactory.getPeriodWork(); RequestQueue requestQueue = periodWork.getRequestQueue();
// Path: flyJenkins/src/main/java/com/agun/flyJenkins/FlyFactory.java // public class FlyFactory { // // public static PeriodWork getPeriodWork(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<PeriodWork> extensionList = jenkins.getExtensionList(PeriodWork.class); // PeriodWork periodWork = extensionList.get(PeriodWork.class); // return periodWork; // } // // public static DeployInfo getDeployInfo(){ // Jenkins jenkins = Jenkins.getInstance(); // ExtensionList<DeployInfo> extensionList = jenkins.getExtensionList(DeployInfo.class); // DeployInfo deployInfo = extensionList.get(DeployInfo.class); // return deployInfo; // } // // public static IncreaseIndexer getIncreaseIndexer(){ // return IncreaseIndexer.getInstance(); // } // // public static Map<String, Object> getPropertiesOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // // List<Item> itemList = jenkins.getAllItems(); // // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getProperties(); // } // } // } // return null; // } // // // public static NetworkSpace getNetworkSpace(){ // return NetworkSpace.getInstance(); // } // // // public static String getRootPathOfJob(String name){ // Jenkins jenkins = Jenkins.getInstance(); // List<Item> itemList = jenkins.getAllItems(); // for(Item item : itemList){ // for(Job job : item.getAllJobs()){ // if(name.equals(job.getName())){ // return job.getRootDir().getAbsolutePath(); // } // } // } // return null; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestMap.java // public class RequestMap { // int type; // Object arg; // // public int getType() { // return type; // } // public void setType(int type) { // this.type = type; // } // public Object getArg() { // return arg; // } // public void setArg(Object arg) { // this.arg = arg; // } // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/request/RequestQueue.java // public class RequestQueue { // // private Map<String, LinkedList<RequestMap>> requestQueueMap = new Hashtable<String, LinkedList<RequestMap>>(); // // public LinkedList<RequestMap> getRequest(String host){ // if(requestQueueMap.containsKey(host)){ // return requestQueueMap.get(host); // } // return null; // } // // // public void add(String host, RequestMap requestMap){ // if(requestQueueMap.containsKey(host)){ // requestQueueMap.get(host).add(requestMap); // }else{ // LinkedList<RequestMap> requestQueue = new LinkedList<RequestMap>(); // requestQueue.add(requestMap); // requestQueueMap.put(host, requestQueue); // } // } // // } // // Path: flyJenkins/src/main/java/com/agun/flyJenkins/schedule/PeriodWork.java // @Extension // public class PeriodWork extends PeriodicWork { // // private RequestQueue requestQueue = new RequestQueue(); // private DeploySurveillant deploySurveillant = new DeploySurveillant(); // // public RequestQueue getRequestQueue(){ // return requestQueue; // } // // public DeploySurveillant getDeploySurveillant(){ // return deploySurveillant; // } // // public Map<String, DeployReport> getDeployReportMap(){ // return deploySurveillant.getDeployReportMap(); // } // // @Override // public long getRecurrencePeriod() { // //return MIN; // return 10000; // } // // @IgnoreJRERequirement // @Override // protected void doRun() throws Exception { // deploySurveillant.process(); // } // } // Path: flyJenkins/src/main/java/com/agun/flyJenkins/process/FlyRequester.java import java.util.Collections; import java.util.Hashtable; import java.util.LinkedList; import java.util.Map; import com.agun.flyJenkins.FlyFactory; import com.agun.flyJenkins.request.RequestMap; import com.agun.flyJenkins.request.RequestQueue; import com.agun.flyJenkins.schedule.PeriodWork; package com.agun.flyJenkins.process; public class FlyRequester implements FlyProcess { private static FlyRequester flyRequester = new FlyRequester(); private FlyRequester(){ } public static FlyRequester getInstance(){ return FlyRequester.flyRequester; } private Map<String, Object> peekRequest(String host){ PeriodWork periodWork = FlyFactory.getPeriodWork(); RequestQueue requestQueue = periodWork.getRequestQueue();
LinkedList<RequestMap> requestLinkedList = requestQueue.getRequest(host);
agune/flyJenkins
flyAgent/src/main/java/com/agun/jenkins/ProcessTreeHelper.java
// Path: flyAgent/src/main/java/com/agun/system/SystemUtil.java // public class SystemUtil { // public static boolean isWindows(){ // String OS = System.getProperty("os.name").toLowerCase(); // return (OS.indexOf("win") >= 0); // } // }
import hudson.util.ProcessTree; import hudson.util.ProcessTree.OSProcess; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import com.agun.system.SystemUtil;
/*** * jenkins 의 ProcessTree 기능을 편하게 사용할 수 있게 추상화 * @author agun */ package com.agun.jenkins; public class ProcessTreeHelper { /** * OSProcess 의 iterator 을 편한 List<?>로 변경해 준다 * @return List<OSProcess> */ public static List<OSProcess> getProcessList(){ ProcessTree processTree = ProcessTree.get(); Iterator<OSProcess> processIter = processTree.iterator(); List<OSProcess> processList = new ArrayList<OSProcess>(); while(processIter.hasNext()){ processList.add(processIter.next()); } return processList; } /** * 프로세스에 대한 정보를 구한다. * @return Map<Integer, String> */ public static Map<Integer, String> getInfoProcess(){ ProcessTree processTree = ProcessTree.get(); Iterator<OSProcess> processIter = processTree.iterator(); Map<Integer, String> processInfoMap = new Hashtable<Integer, String>(); while(processIter.hasNext()){ OSProcess osProcess = processIter.next(); // windowns ? org.jvnet.winp.WinpException: Failed to open process error=5 at .\envvar-cmdline.cpp:53
// Path: flyAgent/src/main/java/com/agun/system/SystemUtil.java // public class SystemUtil { // public static boolean isWindows(){ // String OS = System.getProperty("os.name").toLowerCase(); // return (OS.indexOf("win") >= 0); // } // } // Path: flyAgent/src/main/java/com/agun/jenkins/ProcessTreeHelper.java import hudson.util.ProcessTree; import hudson.util.ProcessTree.OSProcess; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import com.agun.system.SystemUtil; /*** * jenkins 의 ProcessTree 기능을 편하게 사용할 수 있게 추상화 * @author agun */ package com.agun.jenkins; public class ProcessTreeHelper { /** * OSProcess 의 iterator 을 편한 List<?>로 변경해 준다 * @return List<OSProcess> */ public static List<OSProcess> getProcessList(){ ProcessTree processTree = ProcessTree.get(); Iterator<OSProcess> processIter = processTree.iterator(); List<OSProcess> processList = new ArrayList<OSProcess>(); while(processIter.hasNext()){ processList.add(processIter.next()); } return processList; } /** * 프로세스에 대한 정보를 구한다. * @return Map<Integer, String> */ public static Map<Integer, String> getInfoProcess(){ ProcessTree processTree = ProcessTree.get(); Iterator<OSProcess> processIter = processTree.iterator(); Map<Integer, String> processInfoMap = new Hashtable<Integer, String>(); while(processIter.hasNext()){ OSProcess osProcess = processIter.next(); // windowns ? org.jvnet.winp.WinpException: Failed to open process error=5 at .\envvar-cmdline.cpp:53
if(SystemUtil.isWindows()){
TouK/influxdb-reporter
hikariCP-tracker/src/main/java/influxdbreporter/InfluxdbReporterMetricsTracker.java
// Path: http-client-java-wrapper/src/main/java/influxdbreporter/javawrapper/MetricRegistry.java // public class MetricRegistry { // // final influxdbreporter.core.MetricRegistry scalaRegistry; // // public MetricRegistry(String prefix) { // scalaRegistry = MetricRegistry$.MODULE$.apply(prefix); // } // // public MetricRegistry(influxdbreporter.core.MetricRegistry scalaRegistry) { // this.scalaRegistry = scalaRegistry; // } // // public <U extends com.codahale.metrics.Metric, T extends Metric<U>> T register(final String name, final T metric) { // return scalaRegistry.register( // name, // new RegisterMagnet<T>() { // @Override // public T register(String metricName, MetricRegistryImpl registryImpl) { // return registryImpl.registerMetricWithCollector( // name, // metric, // (influxdbreporter.core.collectors.MetricCollector<U>) metricCollectorOfMetric(metric) // ); // } // // @Override // public T registerOrGetRegistered(String metricName, MetricRegistryImpl registryImpl) { // return registryImpl.registerMetricWithCollector( // name, // metric, // (influxdbreporter.core.collectors.MetricCollector<U>) metricCollectorOfMetric(metric) // ); // } // }); // } // // public <U extends com.codahale.metrics.Metric, T extends Metric<U>> T register(final String name, // final T metric, // final MetricCollector<U> collector) { // return scalaRegistry.register( // name, // new RegisterMagnet<T>() { // @Override // public T register(String metricName, MetricRegistryImpl registryImpl) { // return registryImpl.registerMetricWithCollector( // name, // metric, // collector.convertToScalaCollector() // ); // } // // @Override // public T registerOrGetRegistered(String metricName, MetricRegistryImpl registryImpl) { // return registryImpl.registerMetricWithCollector( // name, // metric, // collector.convertToScalaCollector() // ); // } // }); // } // // public void unregister(String name) { // scalaRegistry.unregister(name); // } // // private influxdbreporter.core.collectors.MetricCollector<? extends com.codahale.metrics.Metric> metricCollectorOfMetric(Metric metric) { // if (metric instanceof Counter) return CounterCollector.COLLECTOR; // else if (metric instanceof Histogram) return HistogramCollector.COLLECTOR; // else if (metric instanceof Meter) return MeterCollector.COLLECTOR; // else if (metric instanceof Timer) return TimerCollector.COLLECTOR; // else if (metric instanceof DiscreteGauge) return GaugeCollector.collector(); // else if (metric instanceof PullingGauge) return GaugeCollector.collector(); // else throw new IllegalArgumentException("Unknown metric type: " + metric.getClass().getName()); // } // }
import scala.concurrent.Future; import scala.concurrent.Future$; import com.zaxxer.hikari.metrics.MetricsTracker; import com.zaxxer.hikari.metrics.PoolStats; import java.util.concurrent.TimeUnit; import influxdbreporter.core.Tag; import influxdbreporter.core.metrics.pull.PullingGauge; import influxdbreporter.core.metrics.pull.ValueByTag; import influxdbreporter.javawrapper.MetricRegistry; import influxdbreporter.core.metrics.push.Histogram; import influxdbreporter.core.metrics.push.Meter; import influxdbreporter.core.metrics.push.Timer; import scala.collection.JavaConverters; import scala.collection.immutable.List; import scala.concurrent.ExecutionContext;
/* * Copyright 2015 * * 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 influxdbreporter; public final class InfluxdbReporterMetricsTracker extends MetricsTracker { private final Timer connectionObtainTimer; private final Histogram connectionUsage; private final Meter connectionTimeoutMeter;
// Path: http-client-java-wrapper/src/main/java/influxdbreporter/javawrapper/MetricRegistry.java // public class MetricRegistry { // // final influxdbreporter.core.MetricRegistry scalaRegistry; // // public MetricRegistry(String prefix) { // scalaRegistry = MetricRegistry$.MODULE$.apply(prefix); // } // // public MetricRegistry(influxdbreporter.core.MetricRegistry scalaRegistry) { // this.scalaRegistry = scalaRegistry; // } // // public <U extends com.codahale.metrics.Metric, T extends Metric<U>> T register(final String name, final T metric) { // return scalaRegistry.register( // name, // new RegisterMagnet<T>() { // @Override // public T register(String metricName, MetricRegistryImpl registryImpl) { // return registryImpl.registerMetricWithCollector( // name, // metric, // (influxdbreporter.core.collectors.MetricCollector<U>) metricCollectorOfMetric(metric) // ); // } // // @Override // public T registerOrGetRegistered(String metricName, MetricRegistryImpl registryImpl) { // return registryImpl.registerMetricWithCollector( // name, // metric, // (influxdbreporter.core.collectors.MetricCollector<U>) metricCollectorOfMetric(metric) // ); // } // }); // } // // public <U extends com.codahale.metrics.Metric, T extends Metric<U>> T register(final String name, // final T metric, // final MetricCollector<U> collector) { // return scalaRegistry.register( // name, // new RegisterMagnet<T>() { // @Override // public T register(String metricName, MetricRegistryImpl registryImpl) { // return registryImpl.registerMetricWithCollector( // name, // metric, // collector.convertToScalaCollector() // ); // } // // @Override // public T registerOrGetRegistered(String metricName, MetricRegistryImpl registryImpl) { // return registryImpl.registerMetricWithCollector( // name, // metric, // collector.convertToScalaCollector() // ); // } // }); // } // // public void unregister(String name) { // scalaRegistry.unregister(name); // } // // private influxdbreporter.core.collectors.MetricCollector<? extends com.codahale.metrics.Metric> metricCollectorOfMetric(Metric metric) { // if (metric instanceof Counter) return CounterCollector.COLLECTOR; // else if (metric instanceof Histogram) return HistogramCollector.COLLECTOR; // else if (metric instanceof Meter) return MeterCollector.COLLECTOR; // else if (metric instanceof Timer) return TimerCollector.COLLECTOR; // else if (metric instanceof DiscreteGauge) return GaugeCollector.collector(); // else if (metric instanceof PullingGauge) return GaugeCollector.collector(); // else throw new IllegalArgumentException("Unknown metric type: " + metric.getClass().getName()); // } // } // Path: hikariCP-tracker/src/main/java/influxdbreporter/InfluxdbReporterMetricsTracker.java import scala.concurrent.Future; import scala.concurrent.Future$; import com.zaxxer.hikari.metrics.MetricsTracker; import com.zaxxer.hikari.metrics.PoolStats; import java.util.concurrent.TimeUnit; import influxdbreporter.core.Tag; import influxdbreporter.core.metrics.pull.PullingGauge; import influxdbreporter.core.metrics.pull.ValueByTag; import influxdbreporter.javawrapper.MetricRegistry; import influxdbreporter.core.metrics.push.Histogram; import influxdbreporter.core.metrics.push.Meter; import influxdbreporter.core.metrics.push.Timer; import scala.collection.JavaConverters; import scala.collection.immutable.List; import scala.concurrent.ExecutionContext; /* * Copyright 2015 * * 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 influxdbreporter; public final class InfluxdbReporterMetricsTracker extends MetricsTracker { private final Timer connectionObtainTimer; private final Histogram connectionUsage; private final Meter connectionTimeoutMeter;
private final MetricRegistry registry;
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/NodeUtils.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // }
import java.io.File; import java.util.LinkedList; import java.util.List; import com.redhat.ceylon.cmr.api.CmrRepository; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode;
/* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * Node utils. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public final class NodeUtils { private static final String INFO = ".repository"; /** * Navigate to node. * * @param root the root * @param tokens the tokens * @return found node or null */
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/NodeUtils.java import java.io.File; import java.util.LinkedList; import java.util.List; import com.redhat.ceylon.cmr.api.CmrRepository; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; /* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * Node utils. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public final class NodeUtils { private static final String INFO = ".repository"; /** * Navigate to node. * * @param root the root * @param tokens the tokens * @return found node or null */
public static Node getNode(Node root, Iterable<String> tokens) {
ceylon/ceylon-module-resolver
api/src/main/java/com/redhat/ceylon/cmr/api/ArtifactContext.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // }
import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; import com.redhat.ceylon.cmr.spi.ContentOptions; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.model.cmr.ArtifactResult; import com.redhat.ceylon.model.cmr.Repository; import com.redhat.ceylon.model.cmr.RepositoryException;
} public ArtifactContext getSuffixContext(String... suffixes) { ArtifactContext ac = copy(); ac.setSuffixes(suffixes); return ac; } public ArtifactContext getDocsContext() { return getSuffixContext(DOCS); } public ArtifactContext getResourcesContext() { return getSuffixContext(RESOURCES); } public ArtifactContext getModuleProperties() { return getSuffixContext(MODULE_PROPERTIES); } public ArtifactContext getModuleXml() { return getSuffixContext(MODULE_XML); } public ArtifactContext getSibling(ArtifactResult result, String... suffixes) { ArtifactContext sibling = new ArtifactContext(result.name(), result.version(), result.repository(), suffixes); sibling.copySettingsFrom(this); return sibling; }
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // Path: api/src/main/java/com/redhat/ceylon/cmr/api/ArtifactContext.java import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; import com.redhat.ceylon.cmr.spi.ContentOptions; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.model.cmr.ArtifactResult; import com.redhat.ceylon.model.cmr.Repository; import com.redhat.ceylon.model.cmr.RepositoryException; } public ArtifactContext getSuffixContext(String... suffixes) { ArtifactContext ac = copy(); ac.setSuffixes(suffixes); return ac; } public ArtifactContext getDocsContext() { return getSuffixContext(DOCS); } public ArtifactContext getResourcesContext() { return getSuffixContext(RESOURCES); } public ArtifactContext getModuleProperties() { return getSuffixContext(MODULE_PROPERTIES); } public ArtifactContext getModuleXml() { return getSuffixContext(MODULE_XML); } public ArtifactContext getSibling(ArtifactResult result, String... suffixes) { ArtifactContext sibling = new ArtifactContext(result.name(), result.version(), result.repository(), suffixes); sibling.copySettingsFrom(this); return sibling; }
public void toNode(Node node) {
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/DefaultNode.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions; import com.redhat.ceylon.cmr.spi.ContentStore; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream;
/* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * Default node impl. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ @SuppressWarnings({"NullableProblems"}) public class DefaultNode extends AbstractOpenNode { private static final long serialVersionUID = 1L;
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/DefaultNode.java import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions; import com.redhat.ceylon.cmr.spi.ContentStore; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; /* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * Default node impl. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ @SuppressWarnings({"NullableProblems"}) public class DefaultNode extends AbstractOpenNode { private static final long serialVersionUID = 1L;
private transient ContentHandle handle;
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/DefaultNode.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions; import com.redhat.ceylon.cmr.spi.ContentStore; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream;
public boolean isRemote() { return remote; } void setRemote(boolean remote) { this.remote = remote; } @Override public void merge(OpenNode other) { if (other == null) throw new IllegalArgumentException("Null node!"); // Node root = NodeUtils.getRoot(this); // Node or = NodeUtils.getRoot(other); // TODO } @Override public OpenNode addNode(String label, Object value) { try { //noinspection NullableProblems return addNode(label, value, null, ContentOptions.DEFAULT, true); } catch (IOException e) { throw new RuntimeException("Should not be here!", e); } } @Override
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/DefaultNode.java import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions; import com.redhat.ceylon.cmr.spi.ContentStore; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; public boolean isRemote() { return remote; } void setRemote(boolean remote) { this.remote = remote; } @Override public void merge(OpenNode other) { if (other == null) throw new IllegalArgumentException("Null node!"); // Node root = NodeUtils.getRoot(this); // Node or = NodeUtils.getRoot(other); // TODO } @Override public OpenNode addNode(String label, Object value) { try { //noinspection NullableProblems return addNode(label, value, null, ContentOptions.DEFAULT, true); } catch (IOException e) { throw new RuntimeException("Should not be here!", e); } } @Override
public Node removeNode(String label) {
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/DefaultNode.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions; import com.redhat.ceylon.cmr.spi.ContentStore; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream;
return (ch != null && ch.hasBinaries()); } @Override @SuppressWarnings("unchecked") public <T> T getContent(Class<T> contentType) throws IOException { if (File.class.equals(contentType)) { synchronized (this) { if (handle != null) return (T) handle.getContentAsFile(); } final ContentStore cs = findService(ContentStore.class); ContentHandle ch = cs.getContent(this); if (ch == null) { ch = HANDLE_MARKER; } synchronized (this) { handle = ch; } return (T) ch.getContentAsFile(); } else { return super.getContent(contentType); } } @Override public InputStream getInputStream() throws IOException {
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/DefaultNode.java import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions; import com.redhat.ceylon.cmr.spi.ContentStore; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; return (ch != null && ch.hasBinaries()); } @Override @SuppressWarnings("unchecked") public <T> T getContent(Class<T> contentType) throws IOException { if (File.class.equals(contentType)) { synchronized (this) { if (handle != null) return (T) handle.getContentAsFile(); } final ContentStore cs = findService(ContentStore.class); ContentHandle ch = cs.getContent(this); if (ch == null) { ch = HANDLE_MARKER; } synchronized (this) { handle = ch; } return (T) ch.getContentAsFile(); } else { return super.getContent(contentType); } } @Override public InputStream getInputStream() throws IOException {
SizedInputStream sizedInputStream = getSizedInputStream();
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/RemoteContentStore.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.common.log.Logger; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions;
/* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * Remote content store. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public class RemoteContentStore extends URLContentStore { public RemoteContentStore(String root, Logger log, boolean offline, int timeout, Proxy proxy) { super(root, log, offline, timeout, proxy); }
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/RemoteContentStore.java import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.common.log.Logger; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions; /* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * Remote content store. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public class RemoteContentStore extends URLContentStore { public RemoteContentStore(String root, Logger log, boolean offline, int timeout, Proxy proxy) { super(root, log, offline, timeout, proxy); }
protected SizedInputStream openSizedStream(final URL url) throws IOException {
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/RemoteContentStore.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.common.log.Logger; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions;
} if (conn instanceof HttpURLConnection) { HttpURLConnection huc = (HttpURLConnection) conn; huc.setConnectTimeout(timeout); huc.setReadTimeout(timeout * Constants.READ_TIMEOUT_MULTIPLIER); addCredentials(huc); try{ InputStream stream = conn.getInputStream(); int code = huc.getResponseCode(); if (code != -1 && code != 200) { log.info("Got " + code + " for url: " + url); return null; } log.debug("Got " + code + " for url: " + url); long contentLength = huc.getContentLengthLong(); return new SizedInputStream(stream, contentLength); }catch(SocketTimeoutException timeoutException){ SocketTimeoutException newException = new SocketTimeoutException("Timed out during connection to "+url); newException.initCause(timeoutException); throw newException; } } } return null; } protected boolean exists(final URL url) throws IOException { return head(url) != null; }
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/RemoteContentStore.java import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.common.log.Logger; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions; } if (conn instanceof HttpURLConnection) { HttpURLConnection huc = (HttpURLConnection) conn; huc.setConnectTimeout(timeout); huc.setReadTimeout(timeout * Constants.READ_TIMEOUT_MULTIPLIER); addCredentials(huc); try{ InputStream stream = conn.getInputStream(); int code = huc.getResponseCode(); if (code != -1 && code != 200) { log.info("Got " + code + " for url: " + url); return null; } log.debug("Got " + code + " for url: " + url); long contentLength = huc.getContentLengthLong(); return new SizedInputStream(stream, contentLength); }catch(SocketTimeoutException timeoutException){ SocketTimeoutException newException = new SocketTimeoutException("Timed out during connection to "+url); newException.initCause(timeoutException); throw newException; } } } return null; } protected boolean exists(final URL url) throws IOException { return head(url) != null; }
public ContentHandle peekContent(Node node) {
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/RemoteContentStore.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.common.log.Logger; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions;
} if (conn instanceof HttpURLConnection) { HttpURLConnection huc = (HttpURLConnection) conn; huc.setConnectTimeout(timeout); huc.setReadTimeout(timeout * Constants.READ_TIMEOUT_MULTIPLIER); addCredentials(huc); try{ InputStream stream = conn.getInputStream(); int code = huc.getResponseCode(); if (code != -1 && code != 200) { log.info("Got " + code + " for url: " + url); return null; } log.debug("Got " + code + " for url: " + url); long contentLength = huc.getContentLengthLong(); return new SizedInputStream(stream, contentLength); }catch(SocketTimeoutException timeoutException){ SocketTimeoutException newException = new SocketTimeoutException("Timed out during connection to "+url); newException.initCause(timeoutException); throw newException; } } } return null; } protected boolean exists(final URL url) throws IOException { return head(url) != null; }
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/RemoteContentStore.java import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.common.log.Logger; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.util.Collections; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions; } if (conn instanceof HttpURLConnection) { HttpURLConnection huc = (HttpURLConnection) conn; huc.setConnectTimeout(timeout); huc.setReadTimeout(timeout * Constants.READ_TIMEOUT_MULTIPLIER); addCredentials(huc); try{ InputStream stream = conn.getInputStream(); int code = huc.getResponseCode(); if (code != -1 && code != 200) { log.info("Got " + code + " for url: " + url); return null; } log.debug("Got " + code + " for url: " + url); long contentLength = huc.getContentLengthLong(); return new SizedInputStream(stream, contentLength); }catch(SocketTimeoutException timeoutException){ SocketTimeoutException newException = new SocketTimeoutException("Timed out during connection to "+url); newException.initCause(timeoutException); throw newException; } } } return null; } protected boolean exists(final URL url) throws IOException { return head(url) != null; }
public ContentHandle peekContent(Node node) {
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/FileContentStore.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import com.redhat.ceylon.cmr.spi.ContentStore; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.cmr.spi.StructureBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions;
/* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * File content store. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public class FileContentStore implements ContentStore, StructureBuilder { private final File root;
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/FileContentStore.java import com.redhat.ceylon.cmr.spi.ContentStore; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.cmr.spi.StructureBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions; /* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * File content store. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public class FileContentStore implements ContentStore, StructureBuilder { private final File root;
private final ConcurrentMap<Node, File> cache = new ConcurrentHashMap<>();
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/FileContentStore.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import com.redhat.ceylon.cmr.spi.ContentStore; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.cmr.spi.StructureBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions;
throw new IllegalArgumentException("Null node"); return getFileInternal(node); } private File getFileInternal(Node node) { if (node == null) return root; File file = cache.get(node); if (file == null) { File parent = getFileInternal(NodeUtils.firstParent(node)); file = new File(parent, node.getLabel()); // bevare of concatinated names; e.g sha1.local cache.put(node, file); } return file; } void removeFile(Node node) { File file = cache.remove(node); if (file == null) file = getFile(node); delete(file, node); } void clear() { cache.clear(); }
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/FileContentStore.java import com.redhat.ceylon.cmr.spi.ContentStore; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.cmr.spi.StructureBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions; throw new IllegalArgumentException("Null node"); return getFileInternal(node); } private File getFileInternal(Node node) { if (node == null) return root; File file = cache.get(node); if (file == null) { File parent = getFileInternal(NodeUtils.firstParent(node)); file = new File(parent, node.getLabel()); // bevare of concatinated names; e.g sha1.local cache.put(node, file); } return file; } void removeFile(Node node) { File file = cache.remove(node); if (file == null) file = getFile(node); delete(file, node); } void clear() { cache.clear(); }
protected ContentHandle createContentHandle(Node owner, File file) {
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/FileContentStore.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import com.redhat.ceylon.cmr.spi.ContentStore; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.cmr.spi.StructureBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions;
throw new IllegalArgumentException("Null node"); if (root.equals(file)) return; File[] files = file.listFiles(); if ((files == null || files.length == 0) && (file.exists() == false || file.delete())) { cache.remove(node); // remove from cache, since probably not used anymore delete(file.getParentFile(), NodeUtils.firstParent(node)); } } private class FileContentHandle implements ContentHandle { protected Node owner; protected File file; private FileContentHandle(Node owner, File file) { this.owner = owner; this.file = file; } public boolean hasBinaries() { return true; } public InputStream getBinariesAsStream() throws IOException { return new FileInputStream(file); }
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/FileContentStore.java import com.redhat.ceylon.cmr.spi.ContentStore; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.cmr.spi.StructureBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.redhat.ceylon.cmr.spi.ContentHandle; import com.redhat.ceylon.cmr.spi.ContentOptions; throw new IllegalArgumentException("Null node"); if (root.equals(file)) return; File[] files = file.listFiles(); if ((files == null || files.length == 0) && (file.exists() == false || file.delete())) { cache.remove(node); // remove from cache, since probably not used anymore delete(file.getParentFile(), NodeUtils.firstParent(node)); } } private class FileContentHandle implements ContentHandle { protected Node owner; protected File file; private FileContentHandle(Node owner, File file) { this.owner = owner; this.file = file; } public boolean hasBinaries() { return true; } public InputStream getBinariesAsStream() throws IOException { return new FileInputStream(file); }
public SizedInputStream getBinariesAsSizedStream() throws IOException {
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/MarkerNode.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import com.redhat.ceylon.cmr.spi.ContentOptions; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream;
/* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * Marker node. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public class MarkerNode extends AbstractOpenNode { private static final long serialVersionUID = 1L; public MarkerNode() { // serialization only } public MarkerNode(String label, Object value) { super(label, value); } @Override public void merge(OpenNode other) { throw new UnsupportedOperationException("Marker node doesn't support merge: " + toString()); } @Override public OpenNode addNode(String label, Object value) { throw new UnsupportedOperationException("Marker node doesn't add node: " + toString()); } @Override public OpenNode createNode(String label) { throw new UnsupportedOperationException("Marker node cannot create node: " + toString()); } @Override public OpenNode addContent(String label, InputStream content, ContentOptions options) throws IOException { throw new UnsupportedOperationException("Marker node doesn't add content: " + toString()); } @Override public <T extends Serializable> OpenNode addContent(String label, T content, ContentOptions options) throws IOException { throw new UnsupportedOperationException("Marker node doesn't add content: " + toString()); } @Override
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/MarkerNode.java import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import com.redhat.ceylon.cmr.spi.ContentOptions; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; /* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * Marker node. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public class MarkerNode extends AbstractOpenNode { private static final long serialVersionUID = 1L; public MarkerNode() { // serialization only } public MarkerNode(String label, Object value) { super(label, value); } @Override public void merge(OpenNode other) { throw new UnsupportedOperationException("Marker node doesn't support merge: " + toString()); } @Override public OpenNode addNode(String label, Object value) { throw new UnsupportedOperationException("Marker node doesn't add node: " + toString()); } @Override public OpenNode createNode(String label) { throw new UnsupportedOperationException("Marker node cannot create node: " + toString()); } @Override public OpenNode addContent(String label, InputStream content, ContentOptions options) throws IOException { throw new UnsupportedOperationException("Marker node doesn't add content: " + toString()); } @Override public <T extends Serializable> OpenNode addContent(String label, T content, ContentOptions options) throws IOException { throw new UnsupportedOperationException("Marker node doesn't add content: " + toString()); } @Override
public Node removeNode(String label) {
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/MarkerNode.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import com.redhat.ceylon.cmr.spi.ContentOptions; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream;
public OpenNode createNode(String label) { throw new UnsupportedOperationException("Marker node cannot create node: " + toString()); } @Override public OpenNode addContent(String label, InputStream content, ContentOptions options) throws IOException { throw new UnsupportedOperationException("Marker node doesn't add content: " + toString()); } @Override public <T extends Serializable> OpenNode addContent(String label, T content, ContentOptions options) throws IOException { throw new UnsupportedOperationException("Marker node doesn't add content: " + toString()); } @Override public Node removeNode(String label) { throw new UnsupportedOperationException("Marker node doesn't remove node: " + toString()); } @Override public boolean hasBinaries() { return false; } @Override public InputStream getInputStream() throws IOException { return null; } @Override
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/MarkerNode.java import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import com.redhat.ceylon.cmr.spi.ContentOptions; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; public OpenNode createNode(String label) { throw new UnsupportedOperationException("Marker node cannot create node: " + toString()); } @Override public OpenNode addContent(String label, InputStream content, ContentOptions options) throws IOException { throw new UnsupportedOperationException("Marker node doesn't add content: " + toString()); } @Override public <T extends Serializable> OpenNode addContent(String label, T content, ContentOptions options) throws IOException { throw new UnsupportedOperationException("Marker node doesn't add content: " + toString()); } @Override public Node removeNode(String label) { throw new UnsupportedOperationException("Marker node doesn't remove node: " + toString()); } @Override public boolean hasBinaries() { return false; } @Override public InputStream getInputStream() throws IOException { return null; } @Override
public SizedInputStream getSizedInputStream() throws IOException {
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/MavenRepositoryHelper.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // }
import java.io.File; import java.net.Proxy; import com.redhat.ceylon.cmr.api.CmrRepository; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.StructureBuilder; import com.redhat.ceylon.common.log.Logger;
throw new IllegalArgumentException("No Maven repository found!"); } public static CmrRepository getMavenRepository() { return new MavenRepository(new MavenContentStore().createRoot()); } public static CmrRepository getMavenRepository(File mvnRepository) { return new MavenRepository(new MavenContentStore(mvnRepository).createRoot()); } public static CmrRepository getMavenRepository(String repositoryURL, Logger log, boolean offline, int timeout, Proxy proxy) { return new MavenRepository(new RemoteContentStore(repositoryURL, log, offline, timeout, proxy).createRoot()); } public static CmrRepository getMavenRepository(StructureBuilder structureBuilder) { return new MavenRepository(structureBuilder.createRoot()); } private static class MavenContentStore extends FileContentStore { private MavenContentStore() { this(getMavenHome()); } private MavenContentStore(File root) { super(root); } @Override
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/MavenRepositoryHelper.java import java.io.File; import java.net.Proxy; import com.redhat.ceylon.cmr.api.CmrRepository; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.StructureBuilder; import com.redhat.ceylon.common.log.Logger; throw new IllegalArgumentException("No Maven repository found!"); } public static CmrRepository getMavenRepository() { return new MavenRepository(new MavenContentStore().createRoot()); } public static CmrRepository getMavenRepository(File mvnRepository) { return new MavenRepository(new MavenContentStore(mvnRepository).createRoot()); } public static CmrRepository getMavenRepository(String repositoryURL, Logger log, boolean offline, int timeout, Proxy proxy) { return new MavenRepository(new RemoteContentStore(repositoryURL, log, offline, timeout, proxy).createRoot()); } public static CmrRepository getMavenRepository(StructureBuilder structureBuilder) { return new MavenRepository(structureBuilder.createRoot()); } private static class MavenContentStore extends FileContentStore { private MavenContentStore() { this(getMavenHome()); } private MavenContentStore(File root) { super(root); } @Override
protected void delete(File file, Node node) {
ceylon/ceylon-module-resolver
api/src/main/java/com/redhat/ceylon/cmr/api/AbstractRepositoryManager.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // }
import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.common.log.Logger; import com.redhat.ceylon.model.cmr.ArtifactResult; import com.redhat.ceylon.model.cmr.RepositoryException;
public File[] resolve(String name, String version) throws RepositoryException { final ArtifactContext context = new ArtifactContext(name, version); return resolve(context); } public File[] resolve(ArtifactContext context) throws RepositoryException { final ArtifactResult result = getArtifactResult(context); return flatten(result); } public File getArtifact(String name, String version) throws RepositoryException { ArtifactContext context = new ArtifactContext(); context.setName(name); context.setVersion(version); return getArtifact(context); } public File getArtifact(ArtifactContext context) throws RepositoryException { final ArtifactResult result = getArtifactResult(context); return (result != null) ? result.artifact() : null; } public ArtifactResult getArtifactResult(String name, String version) throws RepositoryException { ArtifactContext context = new ArtifactContext(); context.setName(name); context.setVersion(version); return getArtifactResult(context); }
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // Path: api/src/main/java/com/redhat/ceylon/cmr/api/AbstractRepositoryManager.java import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.common.log.Logger; import com.redhat.ceylon.model.cmr.ArtifactResult; import com.redhat.ceylon.model.cmr.RepositoryException; public File[] resolve(String name, String version) throws RepositoryException { final ArtifactContext context = new ArtifactContext(name, version); return resolve(context); } public File[] resolve(ArtifactContext context) throws RepositoryException { final ArtifactResult result = getArtifactResult(context); return flatten(result); } public File getArtifact(String name, String version) throws RepositoryException { ArtifactContext context = new ArtifactContext(); context.setName(name); context.setVersion(version); return getArtifact(context); } public File getArtifact(ArtifactContext context) throws RepositoryException { final ArtifactResult result = getArtifactResult(context); return (result != null) ? result.artifact() : null; } public ArtifactResult getArtifactResult(String name, String version) throws RepositoryException { ArtifactContext context = new ArtifactContext(); context.setName(name); context.setVersion(version); return getArtifactResult(context); }
protected ArtifactResult getFolder(ArtifactContext context, Node node) throws RepositoryException {
ceylon/ceylon-module-resolver
maven/src/test/java/com/redhat/ceylon/test/maven/test/AbstractAetherTest.java
// Path: maven/src/main/java/com/redhat/ceylon/cmr/maven/AetherRepository.java // public class AetherRepository extends MavenRepository { // private final AetherUtils utils; // // private AetherRepository(AetherContentStore acs) { // super(acs.createRoot()); // utils = acs.getUtils(); // } // // public static CmrRepository createRepository(Logger log, boolean offline, int timeout) { // return createRepository(log, null, offline, timeout); // } // // public static CmrRepository createRepository(Logger log, String settingsXml, boolean offline, int timeout) { // AetherContentStore acs = new AetherContentStore(log, offline, timeout); // AetherRepository repo = new AetherRepository(acs); // repo.utils.overrideSettingsXml(settingsXml); // return repo; // } // // @Override // public String[] getArtifactNames(ArtifactContext context) { // String name = context.getName(); // final int p = name.contains(":") ? name.lastIndexOf(":") : name.lastIndexOf("."); // // return getArtifactNames(p >= 0 ? name.substring(p + 1) : name, context.getVersion(), context.getSuffixes()); // } // // @Override // protected String toModuleName(Node node) { // ArtifactContext context = ArtifactContext.fromNode(node); // if (context != null) { // return context.getName(); // } // String moduleName = node.getLabel(); // Node parent = NodeUtils.firstParent(node); // String groupId = NodeUtils.getFullPath(parent, "."); // // That's sort of an invariant, but let's be safe // if (groupId.startsWith(".")) // groupId = groupId.substring(1); // moduleName = groupId != null ? groupId + ":" + moduleName : moduleName; // return moduleName; // } // // @Override // protected List<String> getDefaultParentPathInternal(ArtifactContext context) { // return MavenRepository.getParentPath(context); // } // // @Override // public Node findParent(ArtifactContext context) { // if (context.getName().startsWith("ceylon.")) { // return null; // } // return super.findParent(context); // } // // public ArtifactResult getArtifactResultInternal(RepositoryManager manager, Node node) { // return utils.findDependencies(manager, node); // } // // @Override // public void completeVersions(ModuleVersionQuery lookup, ModuleVersionResult result) { // if(lookup.getType() != Type.ALL && lookup.getType() != null){ // boolean ok = false; // for(String suffix : lookup.getType().getSuffixes()){ // if(suffix.equals(ArtifactContext.JAR)){ // ok = true; // break; // } // } // if(!ok) // return; // } // // this means only for explicitly Maven modules that have a ":" // if(lookup.getName().indexOf(':') == -1) // return; // String[] groupArtifactIds = utils.nameToGroupArtifactIds(lookup.getName()); // if(groupArtifactIds == null) // return; // // FIXME: does not respect paging or count // utils.search(groupArtifactIds[0], groupArtifactIds[1], lookup.getVersion(), result, getOverrides(), getDisplayString()); // } // }
import java.io.File; import java.net.URL; import com.redhat.ceylon.cmr.api.CmrRepository; import com.redhat.ceylon.cmr.impl.CMRJULLogger; import com.redhat.ceylon.cmr.maven.AetherRepository; import com.redhat.ceylon.common.log.Logger;
/* * Copyright 2014 Red Hat inc. and third party contributors as noted * by the author tags. * 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.redhat.ceylon.test.maven.test; /** * Abstract Aether tests. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public abstract class AbstractAetherTest { protected static final Logger log = new CMRJULLogger(); protected CmrRepository createAetherRepository() throws Exception { URL settingsURL = getClass().getClassLoader().getResource("maven-settings/settings.xml"); String settingsXml = new File(settingsURL.toURI()).getPath();
// Path: maven/src/main/java/com/redhat/ceylon/cmr/maven/AetherRepository.java // public class AetherRepository extends MavenRepository { // private final AetherUtils utils; // // private AetherRepository(AetherContentStore acs) { // super(acs.createRoot()); // utils = acs.getUtils(); // } // // public static CmrRepository createRepository(Logger log, boolean offline, int timeout) { // return createRepository(log, null, offline, timeout); // } // // public static CmrRepository createRepository(Logger log, String settingsXml, boolean offline, int timeout) { // AetherContentStore acs = new AetherContentStore(log, offline, timeout); // AetherRepository repo = new AetherRepository(acs); // repo.utils.overrideSettingsXml(settingsXml); // return repo; // } // // @Override // public String[] getArtifactNames(ArtifactContext context) { // String name = context.getName(); // final int p = name.contains(":") ? name.lastIndexOf(":") : name.lastIndexOf("."); // // return getArtifactNames(p >= 0 ? name.substring(p + 1) : name, context.getVersion(), context.getSuffixes()); // } // // @Override // protected String toModuleName(Node node) { // ArtifactContext context = ArtifactContext.fromNode(node); // if (context != null) { // return context.getName(); // } // String moduleName = node.getLabel(); // Node parent = NodeUtils.firstParent(node); // String groupId = NodeUtils.getFullPath(parent, "."); // // That's sort of an invariant, but let's be safe // if (groupId.startsWith(".")) // groupId = groupId.substring(1); // moduleName = groupId != null ? groupId + ":" + moduleName : moduleName; // return moduleName; // } // // @Override // protected List<String> getDefaultParentPathInternal(ArtifactContext context) { // return MavenRepository.getParentPath(context); // } // // @Override // public Node findParent(ArtifactContext context) { // if (context.getName().startsWith("ceylon.")) { // return null; // } // return super.findParent(context); // } // // public ArtifactResult getArtifactResultInternal(RepositoryManager manager, Node node) { // return utils.findDependencies(manager, node); // } // // @Override // public void completeVersions(ModuleVersionQuery lookup, ModuleVersionResult result) { // if(lookup.getType() != Type.ALL && lookup.getType() != null){ // boolean ok = false; // for(String suffix : lookup.getType().getSuffixes()){ // if(suffix.equals(ArtifactContext.JAR)){ // ok = true; // break; // } // } // if(!ok) // return; // } // // this means only for explicitly Maven modules that have a ":" // if(lookup.getName().indexOf(':') == -1) // return; // String[] groupArtifactIds = utils.nameToGroupArtifactIds(lookup.getName()); // if(groupArtifactIds == null) // return; // // FIXME: does not respect paging or count // utils.search(groupArtifactIds[0], groupArtifactIds[1], lookup.getVersion(), result, getOverrides(), getDisplayString()); // } // } // Path: maven/src/test/java/com/redhat/ceylon/test/maven/test/AbstractAetherTest.java import java.io.File; import java.net.URL; import com.redhat.ceylon.cmr.api.CmrRepository; import com.redhat.ceylon.cmr.impl.CMRJULLogger; import com.redhat.ceylon.cmr.maven.AetherRepository; import com.redhat.ceylon.common.log.Logger; /* * Copyright 2014 Red Hat inc. and third party contributors as noted * by the author tags. * 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.redhat.ceylon.test.maven.test; /** * Abstract Aether tests. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ public abstract class AbstractAetherTest { protected static final Logger log = new CMRJULLogger(); protected CmrRepository createAetherRepository() throws Exception { URL settingsURL = getClass().getClassLoader().getResource("maven-settings/settings.xml"); String settingsXml = new File(settingsURL.toURI()).getPath();
return AetherRepository.createRepository(log, settingsXml, false, 60000);
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/AbstractOpenNode.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import com.redhat.ceylon.cmr.spi.ContentTransformer; import com.redhat.ceylon.cmr.spi.MergeStrategy; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.cmr.spi.StructureBuilder; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.redhat.ceylon.cmr.spi.ContentHandle;
/* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * Abstract node impl. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ @SuppressWarnings({"NullableProblems"}) public abstract class AbstractOpenNode implements OpenNode, Serializable { private static final long serialVersionUID = 1L; private static final String NODE_MARKER = "#marker#";
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/AbstractOpenNode.java import com.redhat.ceylon.cmr.spi.ContentTransformer; import com.redhat.ceylon.cmr.spi.MergeStrategy; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.cmr.spi.StructureBuilder; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.redhat.ceylon.cmr.spi.ContentHandle; /* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * Abstract node impl. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ @SuppressWarnings({"NullableProblems"}) public abstract class AbstractOpenNode implements OpenNode, Serializable { private static final long serialVersionUID = 1L; private static final String NODE_MARKER = "#marker#";
protected static final ContentHandle HANDLE_MARKER = new ContentHandle() {
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/AbstractOpenNode.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import com.redhat.ceylon.cmr.spi.ContentTransformer; import com.redhat.ceylon.cmr.spi.MergeStrategy; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.cmr.spi.StructureBuilder; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.redhat.ceylon.cmr.spi.ContentHandle;
/* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * Abstract node impl. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ @SuppressWarnings({"NullableProblems"}) public abstract class AbstractOpenNode implements OpenNode, Serializable { private static final long serialVersionUID = 1L; private static final String NODE_MARKER = "#marker#"; protected static final ContentHandle HANDLE_MARKER = new ContentHandle() { public boolean hasBinaries() { return false; } public InputStream getBinariesAsStream() throws IOException { return null; }
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/AbstractOpenNode.java import com.redhat.ceylon.cmr.spi.ContentTransformer; import com.redhat.ceylon.cmr.spi.MergeStrategy; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.cmr.spi.StructureBuilder; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.redhat.ceylon.cmr.spi.ContentHandle; /* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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.redhat.ceylon.cmr.impl; /** * Abstract node impl. * * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> */ @SuppressWarnings({"NullableProblems"}) public abstract class AbstractOpenNode implements OpenNode, Serializable { private static final long serialVersionUID = 1L; private static final String NODE_MARKER = "#marker#"; protected static final ContentHandle HANDLE_MARKER = new ContentHandle() { public boolean hasBinaries() { return false; } public InputStream getBinariesAsStream() throws IOException { return null; }
public SizedInputStream getBinariesAsSizedStream() throws IOException {
ceylon/ceylon-module-resolver
impl/src/main/java/com/redhat/ceylon/cmr/impl/AbstractOpenNode.java
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // }
import com.redhat.ceylon.cmr.spi.ContentTransformer; import com.redhat.ceylon.cmr.spi.MergeStrategy; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.cmr.spi.StructureBuilder; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.redhat.ceylon.cmr.spi.ContentHandle;
public long getSize() throws IOException { return -1L; } public void clean() { } }; private String label; private Object value; private final ConcurrentMap<String, OpenNode> parents = new ConcurrentHashMap<>(); private final ConcurrentMap<String, OpenNode> children = new ConcurrentHashMap<>(); private transient final Map<Class<?>, Object> services = new WeakHashMap<>(); public AbstractOpenNode() { // serialization only } public AbstractOpenNode(String label, Object value) { this.label = label; this.value = value; } protected <T> T findService(Class<T> serviceType) { T service = getService(serviceType); if (service != null) return service;
// Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/ContentHandle.java // public interface ContentHandle { // /** // * Do we have binaries behind this contant. // * e.g. it can be a folder, where we know how to get File, but no real content // * // * @return true if there is real content, false otherwise // */ // boolean hasBinaries(); // // /** // * Get node content as stream. // * Return null if there is no binaries. // * // * @return the node's stream // * @throws IOException for any I/O error // * @deprecated see getBinariesAsSizedStream // */ // InputStream getBinariesAsStream() throws IOException; // // /** // * Get node content as sized stream. // * Return null if there is no binaries. // * // * @return the node's sized stream // * @throws IOException for any I/O error // */ // SizedInputStream getBinariesAsSizedStream() throws IOException; // // /** // * Get node content as file. // * // * @return the node's stream // * @throws IOException for any I/O error // */ // File getContentAsFile() throws IOException; // // /** // * Get last modified timestamp. // * If last modified is undefined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getLastModified() throws IOException; // // /** // * Get size. // * If size cannot be determined, return -1. // * // * @return the last modified, or -1 if undefined // * @throws IOException for any I/O error // */ // long getSize() throws IOException; // // /** // * Cleanup content. // */ // void clean(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/Node.java // public interface Node { // String getLabel(); // // <T> T getValue(Class<T> valueType); // // Node getChild(String label); // // Iterable<? extends Node> getChildren(); // // boolean hasBinaries(); // // /** // * @deprecated see getSizedInputStream // */ // InputStream getInputStream() throws IOException; // // SizedInputStream getSizedInputStream() throws IOException; // // <T> T getContent(Class<T> contentType) throws IOException; // // long getLastModified() throws IOException; // // long getSize() throws IOException; // // Node getParent(String label); // // Iterable<? extends Node> getParents(); // // boolean isRemote(); // // String getDisplayString(); // // String getStoreDisplayString(); // } // // Path: spi/src/main/java/com/redhat/ceylon/cmr/spi/SizedInputStream.java // public class SizedInputStream { // // public final InputStream inputStream; // /** // * Can be -1 if we don't know its size // */ // public final long size; // // public SizedInputStream(InputStream inputStream, long size){ // this.inputStream = inputStream; // this.size = size; // } // } // Path: impl/src/main/java/com/redhat/ceylon/cmr/impl/AbstractOpenNode.java import com.redhat.ceylon.cmr.spi.ContentTransformer; import com.redhat.ceylon.cmr.spi.MergeStrategy; import com.redhat.ceylon.cmr.spi.Node; import com.redhat.ceylon.cmr.spi.OpenNode; import com.redhat.ceylon.cmr.spi.SizedInputStream; import com.redhat.ceylon.cmr.spi.StructureBuilder; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.redhat.ceylon.cmr.spi.ContentHandle; public long getSize() throws IOException { return -1L; } public void clean() { } }; private String label; private Object value; private final ConcurrentMap<String, OpenNode> parents = new ConcurrentHashMap<>(); private final ConcurrentMap<String, OpenNode> children = new ConcurrentHashMap<>(); private transient final Map<Class<?>, Object> services = new WeakHashMap<>(); public AbstractOpenNode() { // serialization only } public AbstractOpenNode(String label, Object value) { this.label = label; this.value = value; } protected <T> T findService(Class<T> serviceType) { T service = getService(serviceType); if (service != null) return service;
for (Node parent : getParents()) {
softwaremill/akka-http-session
example/src/main/java/com/softwaremill/example/session/SessionInvalidationJava.java
// Path: core/src/main/java/com/softwaremill/session/javadsl/HttpSessionAwareDirectives.java // public class HttpSessionAwareDirectives<T> extends AllDirectives { // // private final SessionManager<T> sessionManager; // // public HttpSessionAwareDirectives(SessionManager<T> sessionManager) { // this.sessionManager = sessionManager; // } // // public Route session(SessionContinuity sc, GetSessionTransport st, Function<SessionResult<T>, Route> continuity) { // return SessionDirectives$.MODULE$.session(sc, st, continuity); // } // // public Route setSession(SessionContinuity sc, SetSessionTransport st, T session, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.setSession(sc, st, session, continuity); // } // // public Route optionalSession(SessionContinuity sc, SetSessionTransport st, Function<Optional<T>, Route> continuity) { // return SessionDirectives$.MODULE$.optionalSession(sc, st, continuity); // } // // public Route requiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.requiredSession(sc, st, continuity); // } // // public Route touchRequiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.touchRequiredSession(sc, st, continuity); // } // // public Route invalidateSession(SessionContinuity<T> sc, SetSessionTransport st, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.invalidateSession(sc, st, continuity); // } // // public Route setNewCsrfToken(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.setNewCsrfToken(checkHeader, continuity); // } // // public Route randomTokenCsrfProtection(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.randomTokenCsrfProtection(checkHeader, continuity); // } // // public SessionManager<T> getSessionManager() { // return sessionManager; // } // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$;
import akka.NotUsed; import akka.actor.ActorSystem; import akka.dispatch.MessageDispatcher; import akka.http.javadsl.ConnectHttp; import akka.http.javadsl.Http; import akka.http.javadsl.ServerBinding; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.HttpResponse; import akka.http.javadsl.server.Route; import akka.stream.ActorMaterializer; import akka.stream.javadsl.Flow; import com.softwaremill.session.BasicSessionEncoder; import com.softwaremill.session.CheckHeader; import com.softwaremill.session.RefreshTokenStorage; import com.softwaremill.session.Refreshable; import com.softwaremill.session.SessionConfig; import com.softwaremill.session.SessionEncoder; import com.softwaremill.session.SessionManager; import com.softwaremill.session.SetSessionTransport; import com.softwaremill.session.javadsl.HttpSessionAwareDirectives; import com.softwaremill.session.javadsl.InMemoryRefreshTokenStorage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.CompletionStage; import static com.softwaremill.session.javadsl.SessionTransports.CookieST;
package com.softwaremill.example.session; public class SessionInvalidationJava extends HttpSessionAwareDirectives<MyJavaSession> { private static final Logger LOGGER = LoggerFactory.getLogger(SessionInvalidationJava.class); private static final String SECRET = "c05ll3lesrinf39t7mc5h6un6r0c69lgfno69dsak3vabeqamouq4328cuaekros401ajdpkh60rrtpd8ro24rbuqmgtnd1ebag6ljnb65i8a55d482ok7o0nch0bfbe"; private static final SessionEncoder<MyJavaSession> BASIC_ENCODER = new BasicSessionEncoder<>(MyJavaSession.getSerializer()); // in-memory refresh token storage private static final RefreshTokenStorage<MyJavaSession> REFRESH_TOKEN_STORAGE = new InMemoryRefreshTokenStorage<MyJavaSession>() { @Override public void log(String msg) { LOGGER.info(msg); } }; private Refreshable<MyJavaSession> refreshable; private SetSessionTransport sessionTransport; public SessionInvalidationJava(MessageDispatcher dispatcher) { super(new SessionManager<>( SessionConfig.defaultConfig(SECRET), BASIC_ENCODER ) ); // use Refreshable for sessions, which needs to be refreshed or OneOff otherwise // using Refreshable, a refresh token is set in form of a cookie or a custom header refreshable = new Refreshable<>(getSessionManager(), REFRESH_TOKEN_STORAGE, dispatcher); // set the session transport - based on Cookies (or Headers)
// Path: core/src/main/java/com/softwaremill/session/javadsl/HttpSessionAwareDirectives.java // public class HttpSessionAwareDirectives<T> extends AllDirectives { // // private final SessionManager<T> sessionManager; // // public HttpSessionAwareDirectives(SessionManager<T> sessionManager) { // this.sessionManager = sessionManager; // } // // public Route session(SessionContinuity sc, GetSessionTransport st, Function<SessionResult<T>, Route> continuity) { // return SessionDirectives$.MODULE$.session(sc, st, continuity); // } // // public Route setSession(SessionContinuity sc, SetSessionTransport st, T session, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.setSession(sc, st, session, continuity); // } // // public Route optionalSession(SessionContinuity sc, SetSessionTransport st, Function<Optional<T>, Route> continuity) { // return SessionDirectives$.MODULE$.optionalSession(sc, st, continuity); // } // // public Route requiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.requiredSession(sc, st, continuity); // } // // public Route touchRequiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.touchRequiredSession(sc, st, continuity); // } // // public Route invalidateSession(SessionContinuity<T> sc, SetSessionTransport st, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.invalidateSession(sc, st, continuity); // } // // public Route setNewCsrfToken(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.setNewCsrfToken(checkHeader, continuity); // } // // public Route randomTokenCsrfProtection(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.randomTokenCsrfProtection(checkHeader, continuity); // } // // public SessionManager<T> getSessionManager() { // return sessionManager; // } // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // Path: example/src/main/java/com/softwaremill/example/session/SessionInvalidationJava.java import akka.NotUsed; import akka.actor.ActorSystem; import akka.dispatch.MessageDispatcher; import akka.http.javadsl.ConnectHttp; import akka.http.javadsl.Http; import akka.http.javadsl.ServerBinding; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.HttpResponse; import akka.http.javadsl.server.Route; import akka.stream.ActorMaterializer; import akka.stream.javadsl.Flow; import com.softwaremill.session.BasicSessionEncoder; import com.softwaremill.session.CheckHeader; import com.softwaremill.session.RefreshTokenStorage; import com.softwaremill.session.Refreshable; import com.softwaremill.session.SessionConfig; import com.softwaremill.session.SessionEncoder; import com.softwaremill.session.SessionManager; import com.softwaremill.session.SetSessionTransport; import com.softwaremill.session.javadsl.HttpSessionAwareDirectives; import com.softwaremill.session.javadsl.InMemoryRefreshTokenStorage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.CompletionStage; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; package com.softwaremill.example.session; public class SessionInvalidationJava extends HttpSessionAwareDirectives<MyJavaSession> { private static final Logger LOGGER = LoggerFactory.getLogger(SessionInvalidationJava.class); private static final String SECRET = "c05ll3lesrinf39t7mc5h6un6r0c69lgfno69dsak3vabeqamouq4328cuaekros401ajdpkh60rrtpd8ro24rbuqmgtnd1ebag6ljnb65i8a55d482ok7o0nch0bfbe"; private static final SessionEncoder<MyJavaSession> BASIC_ENCODER = new BasicSessionEncoder<>(MyJavaSession.getSerializer()); // in-memory refresh token storage private static final RefreshTokenStorage<MyJavaSession> REFRESH_TOKEN_STORAGE = new InMemoryRefreshTokenStorage<MyJavaSession>() { @Override public void log(String msg) { LOGGER.info(msg); } }; private Refreshable<MyJavaSession> refreshable; private SetSessionTransport sessionTransport; public SessionInvalidationJava(MessageDispatcher dispatcher) { super(new SessionManager<>( SessionConfig.defaultConfig(SECRET), BASIC_ENCODER ) ); // use Refreshable for sessions, which needs to be refreshed or OneOff otherwise // using Refreshable, a refresh token is set in form of a cookie or a custom header refreshable = new Refreshable<>(getSessionManager(), REFRESH_TOKEN_STORAGE, dispatcher); // set the session transport - based on Cookies (or Headers)
sessionTransport = CookieST;
softwaremill/akka-http-session
example/src/main/java/com/softwaremill/example/jwt/JavaJwtExample.java
// Path: core/src/main/java/com/softwaremill/session/javadsl/HttpSessionAwareDirectives.java // public class HttpSessionAwareDirectives<T> extends AllDirectives { // // private final SessionManager<T> sessionManager; // // public HttpSessionAwareDirectives(SessionManager<T> sessionManager) { // this.sessionManager = sessionManager; // } // // public Route session(SessionContinuity sc, GetSessionTransport st, Function<SessionResult<T>, Route> continuity) { // return SessionDirectives$.MODULE$.session(sc, st, continuity); // } // // public Route setSession(SessionContinuity sc, SetSessionTransport st, T session, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.setSession(sc, st, session, continuity); // } // // public Route optionalSession(SessionContinuity sc, SetSessionTransport st, Function<Optional<T>, Route> continuity) { // return SessionDirectives$.MODULE$.optionalSession(sc, st, continuity); // } // // public Route requiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.requiredSession(sc, st, continuity); // } // // public Route touchRequiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.touchRequiredSession(sc, st, continuity); // } // // public Route invalidateSession(SessionContinuity<T> sc, SetSessionTransport st, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.invalidateSession(sc, st, continuity); // } // // public Route setNewCsrfToken(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.setNewCsrfToken(checkHeader, continuity); // } // // public Route randomTokenCsrfProtection(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.randomTokenCsrfProtection(checkHeader, continuity); // } // // public SessionManager<T> getSessionManager() { // return sessionManager; // } // } // // Path: jwt/src/main/java/com/softwaremill/session/javadsl/JwtSessionSerializers.java // public final class JwtSessionSerializers { // // public static final DefaultFormats$ DefaultUtcDateFormat = DefaultFormats$.MODULE$; // // public static final SessionSerializer<String, JValue> StringToJValueSessionSerializer = JValueSessionSerializer$.MODULE$.stringToJValueSessionSerializer(); // public static final SessionSerializer<Integer, JValue> IntToJValueSessionSerializer = (SessionSerializer<Integer, JValue>) (SessionSerializer) JValueSessionSerializer$.MODULE$.intToJValueSessionSerializer(); // public static final SessionSerializer<Long, JValue> LongToJValueSessionSerializer = (SessionSerializer<Long, JValue>) (SessionSerializer) JValueSessionSerializer$.MODULE$.longToJValueSessionSerializer(); // public static final SessionSerializer<Float, JValue> FloatToJValueSessionSerializer = (SessionSerializer<Float, JValue>) (SessionSerializer) JValueSessionSerializer$.MODULE$.floatToJValueSessionSerializer(); // public static final SessionSerializer<Double, JValue> DoubleToJValueSessionSerializer = (SessionSerializer<Double, JValue>) (SessionSerializer) JValueSessionSerializer$.MODULE$.doubleToJValueSessionSerializer(); // // private JwtSessionSerializers() { // } // // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$;
import akka.NotUsed; import akka.actor.ActorSystem; import akka.dispatch.MessageDispatcher; import akka.http.javadsl.ConnectHttp; import akka.http.javadsl.Http; import akka.http.javadsl.ServerBinding; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.HttpResponse; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.Uri; import akka.http.javadsl.server.Route; import akka.http.javadsl.unmarshalling.Unmarshaller; import akka.stream.ActorMaterializer; import akka.stream.javadsl.Flow; import com.softwaremill.session.CheckHeader; import com.softwaremill.session.JwtSessionEncoder; import com.softwaremill.session.RefreshTokenStorage; import com.softwaremill.session.Refreshable; import com.softwaremill.session.SessionConfig; import com.softwaremill.session.SessionEncoder; import com.softwaremill.session.SessionManager; import com.softwaremill.session.SetSessionTransport; import com.softwaremill.session.javadsl.HttpSessionAwareDirectives; import com.softwaremill.session.javadsl.InMemoryRefreshTokenStorage; import com.softwaremill.session.javadsl.JwtSessionSerializers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.CompletionStage; import static com.softwaremill.session.javadsl.SessionTransports.CookieST;
package com.softwaremill.example.jwt; public class JavaJwtExample extends HttpSessionAwareDirectives<String> { private static final Logger LOGGER = LoggerFactory.getLogger(JavaJwtExample.class); private static final String SECRET = "c05ll3lesrinf39t7mc5h6un6r0c69lgfno69dsak3vabeqamouq4328cuaekros401ajdpkh60rrtpd8ro24rbuqmgtnd1ebag6ljnb65i8a55d482ok7o0nch0bfbe";
// Path: core/src/main/java/com/softwaremill/session/javadsl/HttpSessionAwareDirectives.java // public class HttpSessionAwareDirectives<T> extends AllDirectives { // // private final SessionManager<T> sessionManager; // // public HttpSessionAwareDirectives(SessionManager<T> sessionManager) { // this.sessionManager = sessionManager; // } // // public Route session(SessionContinuity sc, GetSessionTransport st, Function<SessionResult<T>, Route> continuity) { // return SessionDirectives$.MODULE$.session(sc, st, continuity); // } // // public Route setSession(SessionContinuity sc, SetSessionTransport st, T session, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.setSession(sc, st, session, continuity); // } // // public Route optionalSession(SessionContinuity sc, SetSessionTransport st, Function<Optional<T>, Route> continuity) { // return SessionDirectives$.MODULE$.optionalSession(sc, st, continuity); // } // // public Route requiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.requiredSession(sc, st, continuity); // } // // public Route touchRequiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.touchRequiredSession(sc, st, continuity); // } // // public Route invalidateSession(SessionContinuity<T> sc, SetSessionTransport st, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.invalidateSession(sc, st, continuity); // } // // public Route setNewCsrfToken(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.setNewCsrfToken(checkHeader, continuity); // } // // public Route randomTokenCsrfProtection(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.randomTokenCsrfProtection(checkHeader, continuity); // } // // public SessionManager<T> getSessionManager() { // return sessionManager; // } // } // // Path: jwt/src/main/java/com/softwaremill/session/javadsl/JwtSessionSerializers.java // public final class JwtSessionSerializers { // // public static final DefaultFormats$ DefaultUtcDateFormat = DefaultFormats$.MODULE$; // // public static final SessionSerializer<String, JValue> StringToJValueSessionSerializer = JValueSessionSerializer$.MODULE$.stringToJValueSessionSerializer(); // public static final SessionSerializer<Integer, JValue> IntToJValueSessionSerializer = (SessionSerializer<Integer, JValue>) (SessionSerializer) JValueSessionSerializer$.MODULE$.intToJValueSessionSerializer(); // public static final SessionSerializer<Long, JValue> LongToJValueSessionSerializer = (SessionSerializer<Long, JValue>) (SessionSerializer) JValueSessionSerializer$.MODULE$.longToJValueSessionSerializer(); // public static final SessionSerializer<Float, JValue> FloatToJValueSessionSerializer = (SessionSerializer<Float, JValue>) (SessionSerializer) JValueSessionSerializer$.MODULE$.floatToJValueSessionSerializer(); // public static final SessionSerializer<Double, JValue> DoubleToJValueSessionSerializer = (SessionSerializer<Double, JValue>) (SessionSerializer) JValueSessionSerializer$.MODULE$.doubleToJValueSessionSerializer(); // // private JwtSessionSerializers() { // } // // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // Path: example/src/main/java/com/softwaremill/example/jwt/JavaJwtExample.java import akka.NotUsed; import akka.actor.ActorSystem; import akka.dispatch.MessageDispatcher; import akka.http.javadsl.ConnectHttp; import akka.http.javadsl.Http; import akka.http.javadsl.ServerBinding; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.HttpResponse; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.Uri; import akka.http.javadsl.server.Route; import akka.http.javadsl.unmarshalling.Unmarshaller; import akka.stream.ActorMaterializer; import akka.stream.javadsl.Flow; import com.softwaremill.session.CheckHeader; import com.softwaremill.session.JwtSessionEncoder; import com.softwaremill.session.RefreshTokenStorage; import com.softwaremill.session.Refreshable; import com.softwaremill.session.SessionConfig; import com.softwaremill.session.SessionEncoder; import com.softwaremill.session.SessionManager; import com.softwaremill.session.SetSessionTransport; import com.softwaremill.session.javadsl.HttpSessionAwareDirectives; import com.softwaremill.session.javadsl.InMemoryRefreshTokenStorage; import com.softwaremill.session.javadsl.JwtSessionSerializers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.CompletionStage; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; package com.softwaremill.example.jwt; public class JavaJwtExample extends HttpSessionAwareDirectives<String> { private static final Logger LOGGER = LoggerFactory.getLogger(JavaJwtExample.class); private static final String SECRET = "c05ll3lesrinf39t7mc5h6un6r0c69lgfno69dsak3vabeqamouq4328cuaekros401ajdpkh60rrtpd8ro24rbuqmgtnd1ebag6ljnb65i8a55d482ok7o0nch0bfbe";
private static final SessionEncoder<String> JWT_ENCODER = new JwtSessionEncoder<>(JwtSessionSerializers.StringToJValueSessionSerializer, JwtSessionSerializers.DefaultUtcDateFormat);
softwaremill/akka-http-session
javaTests/src/test/java/com/softwaremill/session/javadsl/RefreshableTest.java
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport HeaderST = HeaderST$.MODULE$;
import akka.http.javadsl.model.HttpHeader; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.headers.Cookie; import akka.http.javadsl.model.headers.HttpCookie; import akka.http.javadsl.model.headers.RawHeader; import akka.http.javadsl.server.Route; import akka.http.javadsl.testkit.TestRouteResult; import akka.http.scaladsl.model.HttpResponse; import com.softwaremill.session.CsrfCheckMode; import com.softwaremill.session.SessionContinuity; import com.softwaremill.session.SetSessionTransport; import org.junit.Assert; import org.junit.Test; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; import static com.softwaremill.session.javadsl.SessionTransports.HeaderST;
package com.softwaremill.session.javadsl; public class RefreshableTest extends HttpSessionAwareDirectivesTest { protected Route buildRoute(HttpSessionAwareDirectives<String> testDirectives, SessionContinuity<String> oneOff, SessionContinuity<String> refreshable, SetSessionTransport sessionTransport, CsrfCheckMode<String> checkHeader) { return route( path("set", () -> testDirectives.setSession(refreshable, sessionTransport, SESSION, () -> complete("ok")) ), path("getOpt", () -> testDirectives.optionalSession(refreshable, sessionTransport, session -> complete(session.toString())) ), path("getReq", () -> testDirectives.requiredSession(refreshable, sessionTransport, session -> complete(session)) ), path("touchReq", () -> testDirectives.touchRequiredSession(refreshable, sessionTransport, session -> complete(session)) ), path("invalidate", () -> testDirectives.invalidateSession(refreshable, sessionTransport, () -> complete("ok")) ), path("full", () -> testDirectives.session(refreshable, sessionTransport, sessionResult -> complete(sessionResult.toString())) ) ); } @Test public void shouldSetTheRefreshTokenCookieToExpireWhen_UsingCookies() { // given
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport HeaderST = HeaderST$.MODULE$; // Path: javaTests/src/test/java/com/softwaremill/session/javadsl/RefreshableTest.java import akka.http.javadsl.model.HttpHeader; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.headers.Cookie; import akka.http.javadsl.model.headers.HttpCookie; import akka.http.javadsl.model.headers.RawHeader; import akka.http.javadsl.server.Route; import akka.http.javadsl.testkit.TestRouteResult; import akka.http.scaladsl.model.HttpResponse; import com.softwaremill.session.CsrfCheckMode; import com.softwaremill.session.SessionContinuity; import com.softwaremill.session.SetSessionTransport; import org.junit.Assert; import org.junit.Test; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; import static com.softwaremill.session.javadsl.SessionTransports.HeaderST; package com.softwaremill.session.javadsl; public class RefreshableTest extends HttpSessionAwareDirectivesTest { protected Route buildRoute(HttpSessionAwareDirectives<String> testDirectives, SessionContinuity<String> oneOff, SessionContinuity<String> refreshable, SetSessionTransport sessionTransport, CsrfCheckMode<String> checkHeader) { return route( path("set", () -> testDirectives.setSession(refreshable, sessionTransport, SESSION, () -> complete("ok")) ), path("getOpt", () -> testDirectives.optionalSession(refreshable, sessionTransport, session -> complete(session.toString())) ), path("getReq", () -> testDirectives.requiredSession(refreshable, sessionTransport, session -> complete(session)) ), path("touchReq", () -> testDirectives.touchRequiredSession(refreshable, sessionTransport, session -> complete(session)) ), path("invalidate", () -> testDirectives.invalidateSession(refreshable, sessionTransport, () -> complete("ok")) ), path("full", () -> testDirectives.session(refreshable, sessionTransport, sessionResult -> complete(sessionResult.toString())) ) ); } @Test public void shouldSetTheRefreshTokenCookieToExpireWhen_UsingCookies() { // given
final Route route = createRoute(CookieST);
softwaremill/akka-http-session
javaTests/src/test/java/com/softwaremill/session/javadsl/RefreshableTest.java
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport HeaderST = HeaderST$.MODULE$;
import akka.http.javadsl.model.HttpHeader; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.headers.Cookie; import akka.http.javadsl.model.headers.HttpCookie; import akka.http.javadsl.model.headers.RawHeader; import akka.http.javadsl.server.Route; import akka.http.javadsl.testkit.TestRouteResult; import akka.http.scaladsl.model.HttpResponse; import com.softwaremill.session.CsrfCheckMode; import com.softwaremill.session.SessionContinuity; import com.softwaremill.session.SetSessionTransport; import org.junit.Assert; import org.junit.Test; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; import static com.softwaremill.session.javadsl.SessionTransports.HeaderST;
@Test public void shouldSetBoth_TheSessionAndRefreshTokenWhen_UsingCookies() { // given final Route route = createRoute(CookieST); // when TestRouteResult testRouteResult = testRoute(route) .run(HttpRequest.GET("/set")); // then testRouteResult .assertStatusCode(StatusCodes.OK) .assertEntity("ok"); // and HttpResponse response = testRouteResult.response(); // check _refreshtoken cookie HttpCookie refreshTokenCookie = getRefreshTokenCookieValues(response); Assert.assertNotNull(refreshTokenCookie.value()); // check _sessiondata cookie HttpCookie sessionDataCookie = getSessionDataCookieValues(response); Assert.assertNotNull(sessionDataCookie.value()); } @Test public void shouldSetBoth_TheSessionAndRefreshTokenWhen_UsingHeaders() { // given
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport HeaderST = HeaderST$.MODULE$; // Path: javaTests/src/test/java/com/softwaremill/session/javadsl/RefreshableTest.java import akka.http.javadsl.model.HttpHeader; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.headers.Cookie; import akka.http.javadsl.model.headers.HttpCookie; import akka.http.javadsl.model.headers.RawHeader; import akka.http.javadsl.server.Route; import akka.http.javadsl.testkit.TestRouteResult; import akka.http.scaladsl.model.HttpResponse; import com.softwaremill.session.CsrfCheckMode; import com.softwaremill.session.SessionContinuity; import com.softwaremill.session.SetSessionTransport; import org.junit.Assert; import org.junit.Test; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; import static com.softwaremill.session.javadsl.SessionTransports.HeaderST; @Test public void shouldSetBoth_TheSessionAndRefreshTokenWhen_UsingCookies() { // given final Route route = createRoute(CookieST); // when TestRouteResult testRouteResult = testRoute(route) .run(HttpRequest.GET("/set")); // then testRouteResult .assertStatusCode(StatusCodes.OK) .assertEntity("ok"); // and HttpResponse response = testRouteResult.response(); // check _refreshtoken cookie HttpCookie refreshTokenCookie = getRefreshTokenCookieValues(response); Assert.assertNotNull(refreshTokenCookie.value()); // check _sessiondata cookie HttpCookie sessionDataCookie = getSessionDataCookieValues(response); Assert.assertNotNull(sessionDataCookie.value()); } @Test public void shouldSetBoth_TheSessionAndRefreshTokenWhen_UsingHeaders() { // given
final Route route = createRoute(HeaderST);
softwaremill/akka-http-session
example/src/main/java/com/softwaremill/example/session/VariousSessionsJava.java
// Path: core/src/main/java/com/softwaremill/session/javadsl/HttpSessionAwareDirectives.java // public class HttpSessionAwareDirectives<T> extends AllDirectives { // // private final SessionManager<T> sessionManager; // // public HttpSessionAwareDirectives(SessionManager<T> sessionManager) { // this.sessionManager = sessionManager; // } // // public Route session(SessionContinuity sc, GetSessionTransport st, Function<SessionResult<T>, Route> continuity) { // return SessionDirectives$.MODULE$.session(sc, st, continuity); // } // // public Route setSession(SessionContinuity sc, SetSessionTransport st, T session, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.setSession(sc, st, session, continuity); // } // // public Route optionalSession(SessionContinuity sc, SetSessionTransport st, Function<Optional<T>, Route> continuity) { // return SessionDirectives$.MODULE$.optionalSession(sc, st, continuity); // } // // public Route requiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.requiredSession(sc, st, continuity); // } // // public Route touchRequiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.touchRequiredSession(sc, st, continuity); // } // // public Route invalidateSession(SessionContinuity<T> sc, SetSessionTransport st, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.invalidateSession(sc, st, continuity); // } // // public Route setNewCsrfToken(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.setNewCsrfToken(checkHeader, continuity); // } // // public Route randomTokenCsrfProtection(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.randomTokenCsrfProtection(checkHeader, continuity); // } // // public SessionManager<T> getSessionManager() { // return sessionManager; // } // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$;
import akka.NotUsed; import akka.actor.ActorSystem; import akka.dispatch.MessageDispatcher; import akka.http.javadsl.ConnectHttp; import akka.http.javadsl.Http; import akka.http.javadsl.ServerBinding; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.HttpResponse; import akka.http.javadsl.server.Route; import akka.stream.ActorMaterializer; import akka.stream.javadsl.Flow; import com.softwaremill.session.BasicSessionEncoder; import com.softwaremill.session.CheckHeader; import com.softwaremill.session.OneOff; import com.softwaremill.session.SessionConfig; import com.softwaremill.session.SessionEncoder; import com.softwaremill.session.SessionManager; import com.softwaremill.session.SessionResult; import com.softwaremill.session.SessionResult.Corrupt; import com.softwaremill.session.SessionResult.CreatedFromToken; import com.softwaremill.session.SessionResult.Decoded; import com.softwaremill.session.SessionResult.Expired$; import com.softwaremill.session.SessionResult.NoSession$; import com.softwaremill.session.SessionResult.TokenNotFound$; import com.softwaremill.session.SetSessionTransport; import com.softwaremill.session.javadsl.HttpSessionAwareDirectives; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.CompletionStage; import static com.softwaremill.session.javadsl.SessionTransports.CookieST;
package com.softwaremill.example.session; public class VariousSessionsJava extends HttpSessionAwareDirectives<MyJavaSession> { private static final Logger LOGGER = LoggerFactory.getLogger(VariousSessionsJava.class); private static final String SECRET = "c05ll3lesrinf39t7mc5h6un6r0c69lgfno69dsak3vabeqamouq4328cuaekros401ajdpkh60rrtpd8ro24rbuqmgtnd1ebag6ljnb65i8a55d482ok7o0nch0bfbe"; private static final SessionEncoder<MyJavaSession> BASIC_ENCODER = new BasicSessionEncoder<>(MyJavaSession.getSerializer()); private OneOff<MyJavaSession> oneOff; private SetSessionTransport sessionTransport; public VariousSessionsJava(MessageDispatcher dispatcher) { super(new SessionManager<>( SessionConfig.defaultConfig(SECRET), BASIC_ENCODER ) ); oneOff = new OneOff<>(getSessionManager());
// Path: core/src/main/java/com/softwaremill/session/javadsl/HttpSessionAwareDirectives.java // public class HttpSessionAwareDirectives<T> extends AllDirectives { // // private final SessionManager<T> sessionManager; // // public HttpSessionAwareDirectives(SessionManager<T> sessionManager) { // this.sessionManager = sessionManager; // } // // public Route session(SessionContinuity sc, GetSessionTransport st, Function<SessionResult<T>, Route> continuity) { // return SessionDirectives$.MODULE$.session(sc, st, continuity); // } // // public Route setSession(SessionContinuity sc, SetSessionTransport st, T session, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.setSession(sc, st, session, continuity); // } // // public Route optionalSession(SessionContinuity sc, SetSessionTransport st, Function<Optional<T>, Route> continuity) { // return SessionDirectives$.MODULE$.optionalSession(sc, st, continuity); // } // // public Route requiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.requiredSession(sc, st, continuity); // } // // public Route touchRequiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.touchRequiredSession(sc, st, continuity); // } // // public Route invalidateSession(SessionContinuity<T> sc, SetSessionTransport st, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.invalidateSession(sc, st, continuity); // } // // public Route setNewCsrfToken(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.setNewCsrfToken(checkHeader, continuity); // } // // public Route randomTokenCsrfProtection(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.randomTokenCsrfProtection(checkHeader, continuity); // } // // public SessionManager<T> getSessionManager() { // return sessionManager; // } // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // Path: example/src/main/java/com/softwaremill/example/session/VariousSessionsJava.java import akka.NotUsed; import akka.actor.ActorSystem; import akka.dispatch.MessageDispatcher; import akka.http.javadsl.ConnectHttp; import akka.http.javadsl.Http; import akka.http.javadsl.ServerBinding; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.HttpResponse; import akka.http.javadsl.server.Route; import akka.stream.ActorMaterializer; import akka.stream.javadsl.Flow; import com.softwaremill.session.BasicSessionEncoder; import com.softwaremill.session.CheckHeader; import com.softwaremill.session.OneOff; import com.softwaremill.session.SessionConfig; import com.softwaremill.session.SessionEncoder; import com.softwaremill.session.SessionManager; import com.softwaremill.session.SessionResult; import com.softwaremill.session.SessionResult.Corrupt; import com.softwaremill.session.SessionResult.CreatedFromToken; import com.softwaremill.session.SessionResult.Decoded; import com.softwaremill.session.SessionResult.Expired$; import com.softwaremill.session.SessionResult.NoSession$; import com.softwaremill.session.SessionResult.TokenNotFound$; import com.softwaremill.session.SetSessionTransport; import com.softwaremill.session.javadsl.HttpSessionAwareDirectives; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.CompletionStage; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; package com.softwaremill.example.session; public class VariousSessionsJava extends HttpSessionAwareDirectives<MyJavaSession> { private static final Logger LOGGER = LoggerFactory.getLogger(VariousSessionsJava.class); private static final String SECRET = "c05ll3lesrinf39t7mc5h6un6r0c69lgfno69dsak3vabeqamouq4328cuaekros401ajdpkh60rrtpd8ro24rbuqmgtnd1ebag6ljnb65i8a55d482ok7o0nch0bfbe"; private static final SessionEncoder<MyJavaSession> BASIC_ENCODER = new BasicSessionEncoder<>(MyJavaSession.getSerializer()); private OneOff<MyJavaSession> oneOff; private SetSessionTransport sessionTransport; public VariousSessionsJava(MessageDispatcher dispatcher) { super(new SessionManager<>( SessionConfig.defaultConfig(SECRET), BASIC_ENCODER ) ); oneOff = new OneOff<>(getSessionManager());
sessionTransport = CookieST;
softwaremill/akka-http-session
example/src/main/java/com/softwaremill/example/JavaExample.java
// Path: example/src/main/java/com/softwaremill/example/session/MyJavaSession.java // public class MyJavaSession { // // /** // * This session serializer converts a session type into a value (always a String type). The first two arguments are just conversion functions. // * The third argument is a serializer responsible for preparing the data to be sent/received over the wire. There are some ready-to-use serializers available // * in the com.softwaremill.session.SessionSerializer companion object, like stringToString and mapToString, just to name a few. // */ // private static final SessionSerializer<MyJavaSession, String> serializer = new SingleValueSessionSerializer<>( // (JFunction1<MyJavaSession, String>) (session) -> (session.getUsername()) // , // (JFunction1<String, Try<MyJavaSession>>) (login) -> Try.apply((JFunction0<MyJavaSession>) (() -> new MyJavaSession(login))) // , // SessionSerializers.StringToStringSessionSerializer // ); // // private final String username; // // public MyJavaSession(String username) { // this.username = username; // } // // public static SessionSerializer<MyJavaSession, String> getSerializer() { // return serializer; // } // // public String getUsername() { // return username; // } // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/HttpSessionAwareDirectives.java // public class HttpSessionAwareDirectives<T> extends AllDirectives { // // private final SessionManager<T> sessionManager; // // public HttpSessionAwareDirectives(SessionManager<T> sessionManager) { // this.sessionManager = sessionManager; // } // // public Route session(SessionContinuity sc, GetSessionTransport st, Function<SessionResult<T>, Route> continuity) { // return SessionDirectives$.MODULE$.session(sc, st, continuity); // } // // public Route setSession(SessionContinuity sc, SetSessionTransport st, T session, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.setSession(sc, st, session, continuity); // } // // public Route optionalSession(SessionContinuity sc, SetSessionTransport st, Function<Optional<T>, Route> continuity) { // return SessionDirectives$.MODULE$.optionalSession(sc, st, continuity); // } // // public Route requiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.requiredSession(sc, st, continuity); // } // // public Route touchRequiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.touchRequiredSession(sc, st, continuity); // } // // public Route invalidateSession(SessionContinuity<T> sc, SetSessionTransport st, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.invalidateSession(sc, st, continuity); // } // // public Route setNewCsrfToken(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.setNewCsrfToken(checkHeader, continuity); // } // // public Route randomTokenCsrfProtection(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.randomTokenCsrfProtection(checkHeader, continuity); // } // // public SessionManager<T> getSessionManager() { // return sessionManager; // } // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$;
import akka.NotUsed; import akka.actor.ActorSystem; import akka.dispatch.MessageDispatcher; import akka.http.javadsl.ConnectHttp; import akka.http.javadsl.Http; import akka.http.javadsl.ServerBinding; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.HttpResponse; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.Uri; import akka.http.javadsl.server.Route; import akka.http.javadsl.unmarshalling.Unmarshaller; import akka.stream.ActorMaterializer; import akka.stream.javadsl.Flow; import com.softwaremill.example.session.MyJavaSession; import com.softwaremill.session.BasicSessionEncoder; import com.softwaremill.session.CheckHeader; import com.softwaremill.session.RefreshTokenStorage; import com.softwaremill.session.Refreshable; import com.softwaremill.session.SessionConfig; import com.softwaremill.session.SessionEncoder; import com.softwaremill.session.SessionManager; import com.softwaremill.session.SetSessionTransport; import com.softwaremill.session.javadsl.HttpSessionAwareDirectives; import com.softwaremill.session.javadsl.InMemoryRefreshTokenStorage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.CompletionStage; import static com.softwaremill.session.javadsl.SessionTransports.CookieST;
package com.softwaremill.example; public class JavaExample extends HttpSessionAwareDirectives<MyJavaSession> { private static final Logger LOGGER = LoggerFactory.getLogger(JavaExample.class); private static final String SECRET = "c05ll3lesrinf39t7mc5h6un6r0c69lgfno69dsak3vabeqamouq4328cuaekros401ajdpkh60rrtpd8ro24rbuqmgtnd1ebag6ljnb65i8a55d482ok7o0nch0bfbe"; private static final SessionEncoder<MyJavaSession> BASIC_ENCODER = new BasicSessionEncoder<>(MyJavaSession.getSerializer()); // in-memory refresh token storage private static final RefreshTokenStorage<MyJavaSession> REFRESH_TOKEN_STORAGE = new InMemoryRefreshTokenStorage<MyJavaSession>() { @Override public void log(String msg) { LOGGER.info(msg); } }; private Refreshable<MyJavaSession> refreshable; private SetSessionTransport sessionTransport; public JavaExample(MessageDispatcher dispatcher) { super(new SessionManager<>( SessionConfig.defaultConfig(SECRET), BASIC_ENCODER ) ); // use Refreshable for sessions, which needs to be refreshed or OneOff otherwise // using Refreshable, a refresh token is set in form of a cookie or a custom header refreshable = new Refreshable<>(getSessionManager(), REFRESH_TOKEN_STORAGE, dispatcher); // set the session transport - based on Cookies (or Headers)
// Path: example/src/main/java/com/softwaremill/example/session/MyJavaSession.java // public class MyJavaSession { // // /** // * This session serializer converts a session type into a value (always a String type). The first two arguments are just conversion functions. // * The third argument is a serializer responsible for preparing the data to be sent/received over the wire. There are some ready-to-use serializers available // * in the com.softwaremill.session.SessionSerializer companion object, like stringToString and mapToString, just to name a few. // */ // private static final SessionSerializer<MyJavaSession, String> serializer = new SingleValueSessionSerializer<>( // (JFunction1<MyJavaSession, String>) (session) -> (session.getUsername()) // , // (JFunction1<String, Try<MyJavaSession>>) (login) -> Try.apply((JFunction0<MyJavaSession>) (() -> new MyJavaSession(login))) // , // SessionSerializers.StringToStringSessionSerializer // ); // // private final String username; // // public MyJavaSession(String username) { // this.username = username; // } // // public static SessionSerializer<MyJavaSession, String> getSerializer() { // return serializer; // } // // public String getUsername() { // return username; // } // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/HttpSessionAwareDirectives.java // public class HttpSessionAwareDirectives<T> extends AllDirectives { // // private final SessionManager<T> sessionManager; // // public HttpSessionAwareDirectives(SessionManager<T> sessionManager) { // this.sessionManager = sessionManager; // } // // public Route session(SessionContinuity sc, GetSessionTransport st, Function<SessionResult<T>, Route> continuity) { // return SessionDirectives$.MODULE$.session(sc, st, continuity); // } // // public Route setSession(SessionContinuity sc, SetSessionTransport st, T session, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.setSession(sc, st, session, continuity); // } // // public Route optionalSession(SessionContinuity sc, SetSessionTransport st, Function<Optional<T>, Route> continuity) { // return SessionDirectives$.MODULE$.optionalSession(sc, st, continuity); // } // // public Route requiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.requiredSession(sc, st, continuity); // } // // public Route touchRequiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.touchRequiredSession(sc, st, continuity); // } // // public Route invalidateSession(SessionContinuity<T> sc, SetSessionTransport st, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.invalidateSession(sc, st, continuity); // } // // public Route setNewCsrfToken(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.setNewCsrfToken(checkHeader, continuity); // } // // public Route randomTokenCsrfProtection(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.randomTokenCsrfProtection(checkHeader, continuity); // } // // public SessionManager<T> getSessionManager() { // return sessionManager; // } // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // Path: example/src/main/java/com/softwaremill/example/JavaExample.java import akka.NotUsed; import akka.actor.ActorSystem; import akka.dispatch.MessageDispatcher; import akka.http.javadsl.ConnectHttp; import akka.http.javadsl.Http; import akka.http.javadsl.ServerBinding; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.HttpResponse; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.Uri; import akka.http.javadsl.server.Route; import akka.http.javadsl.unmarshalling.Unmarshaller; import akka.stream.ActorMaterializer; import akka.stream.javadsl.Flow; import com.softwaremill.example.session.MyJavaSession; import com.softwaremill.session.BasicSessionEncoder; import com.softwaremill.session.CheckHeader; import com.softwaremill.session.RefreshTokenStorage; import com.softwaremill.session.Refreshable; import com.softwaremill.session.SessionConfig; import com.softwaremill.session.SessionEncoder; import com.softwaremill.session.SessionManager; import com.softwaremill.session.SetSessionTransport; import com.softwaremill.session.javadsl.HttpSessionAwareDirectives; import com.softwaremill.session.javadsl.InMemoryRefreshTokenStorage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.CompletionStage; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; package com.softwaremill.example; public class JavaExample extends HttpSessionAwareDirectives<MyJavaSession> { private static final Logger LOGGER = LoggerFactory.getLogger(JavaExample.class); private static final String SECRET = "c05ll3lesrinf39t7mc5h6un6r0c69lgfno69dsak3vabeqamouq4328cuaekros401ajdpkh60rrtpd8ro24rbuqmgtnd1ebag6ljnb65i8a55d482ok7o0nch0bfbe"; private static final SessionEncoder<MyJavaSession> BASIC_ENCODER = new BasicSessionEncoder<>(MyJavaSession.getSerializer()); // in-memory refresh token storage private static final RefreshTokenStorage<MyJavaSession> REFRESH_TOKEN_STORAGE = new InMemoryRefreshTokenStorage<MyJavaSession>() { @Override public void log(String msg) { LOGGER.info(msg); } }; private Refreshable<MyJavaSession> refreshable; private SetSessionTransport sessionTransport; public JavaExample(MessageDispatcher dispatcher) { super(new SessionManager<>( SessionConfig.defaultConfig(SECRET), BASIC_ENCODER ) ); // use Refreshable for sessions, which needs to be refreshed or OneOff otherwise // using Refreshable, a refresh token is set in form of a cookie or a custom header refreshable = new Refreshable<>(getSessionManager(), REFRESH_TOKEN_STORAGE, dispatcher); // set the session transport - based on Cookies (or Headers)
sessionTransport = CookieST;
softwaremill/akka-http-session
example/src/main/java/com/softwaremill/example/session/MyJavaSession.java
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionSerializers.java // public final class SessionSerializers { // // public static final SessionSerializer<String, String> StringToStringSessionSerializer = SessionSerializer$.MODULE$.stringToStringSessionSerializer(); // public static final SessionSerializer<Integer, String> IntToStringSessionSerializer = (SessionSerializer<Integer, String>) (SessionSerializer) SessionSerializer$.MODULE$.intToStringSessionSerializer(); // public static final SessionSerializer<Long, String> LongToStringSessionSerializer = (SessionSerializer<Long, String>) (SessionSerializer) SessionSerializer$.MODULE$.longToStringSessionSerializer(); // public static final SessionSerializer<Float, String> FloatToStringSessionSerializer = (SessionSerializer<Float, String>) (SessionSerializer) SessionSerializer$.MODULE$.floatToStringSessionSerializer(); // public static final SessionSerializer<Double, String> DoubleToStringSessionSerializer = (SessionSerializer<Double, String>) (SessionSerializer) SessionSerializer$.MODULE$.doubleToStringSessionSerializer(); // // public static final SessionSerializer<Map<String, String>, String> MapToStringSessionSerializer = new MultiValueSessionSerializer<>( // (JFunction1<Map<String, String>, scala.collection.immutable.Map<String, String>>) m -> MapConverters.toImmutableMap(m), // (JFunction1<scala.collection.immutable.Map<String, String>, Try<Map<String, String>>>) v1 -> // Try.apply((JFunction0<Map<String, String>>) () -> JavaConverters.mapAsJavaMapConverter(v1).asJava()) // ); // // private SessionSerializers() { // } // // }
import com.softwaremill.session.SessionSerializer; import com.softwaremill.session.SingleValueSessionSerializer; import com.softwaremill.session.javadsl.SessionSerializers; import scala.compat.java8.JFunction0; import scala.compat.java8.JFunction1; import scala.util.Try;
package com.softwaremill.example.session; public class MyJavaSession { /** * This session serializer converts a session type into a value (always a String type). The first two arguments are just conversion functions. * The third argument is a serializer responsible for preparing the data to be sent/received over the wire. There are some ready-to-use serializers available * in the com.softwaremill.session.SessionSerializer companion object, like stringToString and mapToString, just to name a few. */ private static final SessionSerializer<MyJavaSession, String> serializer = new SingleValueSessionSerializer<>( (JFunction1<MyJavaSession, String>) (session) -> (session.getUsername()) , (JFunction1<String, Try<MyJavaSession>>) (login) -> Try.apply((JFunction0<MyJavaSession>) (() -> new MyJavaSession(login))) ,
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionSerializers.java // public final class SessionSerializers { // // public static final SessionSerializer<String, String> StringToStringSessionSerializer = SessionSerializer$.MODULE$.stringToStringSessionSerializer(); // public static final SessionSerializer<Integer, String> IntToStringSessionSerializer = (SessionSerializer<Integer, String>) (SessionSerializer) SessionSerializer$.MODULE$.intToStringSessionSerializer(); // public static final SessionSerializer<Long, String> LongToStringSessionSerializer = (SessionSerializer<Long, String>) (SessionSerializer) SessionSerializer$.MODULE$.longToStringSessionSerializer(); // public static final SessionSerializer<Float, String> FloatToStringSessionSerializer = (SessionSerializer<Float, String>) (SessionSerializer) SessionSerializer$.MODULE$.floatToStringSessionSerializer(); // public static final SessionSerializer<Double, String> DoubleToStringSessionSerializer = (SessionSerializer<Double, String>) (SessionSerializer) SessionSerializer$.MODULE$.doubleToStringSessionSerializer(); // // public static final SessionSerializer<Map<String, String>, String> MapToStringSessionSerializer = new MultiValueSessionSerializer<>( // (JFunction1<Map<String, String>, scala.collection.immutable.Map<String, String>>) m -> MapConverters.toImmutableMap(m), // (JFunction1<scala.collection.immutable.Map<String, String>, Try<Map<String, String>>>) v1 -> // Try.apply((JFunction0<Map<String, String>>) () -> JavaConverters.mapAsJavaMapConverter(v1).asJava()) // ); // // private SessionSerializers() { // } // // } // Path: example/src/main/java/com/softwaremill/example/session/MyJavaSession.java import com.softwaremill.session.SessionSerializer; import com.softwaremill.session.SingleValueSessionSerializer; import com.softwaremill.session.javadsl.SessionSerializers; import scala.compat.java8.JFunction0; import scala.compat.java8.JFunction1; import scala.util.Try; package com.softwaremill.example.session; public class MyJavaSession { /** * This session serializer converts a session type into a value (always a String type). The first two arguments are just conversion functions. * The third argument is a serializer responsible for preparing the data to be sent/received over the wire. There are some ready-to-use serializers available * in the com.softwaremill.session.SessionSerializer companion object, like stringToString and mapToString, just to name a few. */ private static final SessionSerializer<MyJavaSession, String> serializer = new SingleValueSessionSerializer<>( (JFunction1<MyJavaSession, String>) (session) -> (session.getUsername()) , (JFunction1<String, Try<MyJavaSession>>) (login) -> Try.apply((JFunction0<MyJavaSession>) (() -> new MyJavaSession(login))) ,
SessionSerializers.StringToStringSessionSerializer
softwaremill/akka-http-session
javaTests/src/test/java/com/softwaremill/session/javadsl/OneOffTest.java
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport HeaderST = HeaderST$.MODULE$;
import akka.http.javadsl.model.HttpHeader; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.headers.Cookie; import akka.http.javadsl.model.headers.HttpCookie; import akka.http.javadsl.model.headers.RawHeader; import akka.http.javadsl.server.Route; import akka.http.javadsl.testkit.TestRouteResult; import akka.http.scaladsl.model.HttpResponse; import com.softwaremill.session.CsrfCheckMode; import com.softwaremill.session.SessionContinuity; import com.softwaremill.session.SetSessionTransport; import org.junit.Assert; import org.junit.Test; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; import static com.softwaremill.session.javadsl.SessionTransports.HeaderST;
package com.softwaremill.session.javadsl; public class OneOffTest extends HttpSessionAwareDirectivesTest { protected Route buildRoute(HttpSessionAwareDirectives<String> testDirectives, SessionContinuity<String> oneOff, SessionContinuity<String> refreshable, SetSessionTransport sessionTransport, CsrfCheckMode<String> checkHeader) { return route( path("set", () -> testDirectives.setSession(oneOff, sessionTransport, SESSION, () -> complete("ok")) ), path("getOpt", () -> testDirectives.optionalSession(oneOff, sessionTransport, session -> complete(session.toString())) ), path("getReq", () -> testDirectives.requiredSession(oneOff, sessionTransport, session -> complete(session)) ), path("touchReq", () -> testDirectives.touchRequiredSession(oneOff, sessionTransport, session -> complete(session)) ), path("invalidate", () -> testDirectives.invalidateSession(oneOff, sessionTransport, () -> complete("ok")) ), path("full", () -> testDirectives.session(oneOff, sessionTransport, sessionResult -> complete(sessionResult.toString())) ) ); } @Test public void shouldSetTheCorrectSessionCookieName_UsingCookies() { // given
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport HeaderST = HeaderST$.MODULE$; // Path: javaTests/src/test/java/com/softwaremill/session/javadsl/OneOffTest.java import akka.http.javadsl.model.HttpHeader; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.headers.Cookie; import akka.http.javadsl.model.headers.HttpCookie; import akka.http.javadsl.model.headers.RawHeader; import akka.http.javadsl.server.Route; import akka.http.javadsl.testkit.TestRouteResult; import akka.http.scaladsl.model.HttpResponse; import com.softwaremill.session.CsrfCheckMode; import com.softwaremill.session.SessionContinuity; import com.softwaremill.session.SetSessionTransport; import org.junit.Assert; import org.junit.Test; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; import static com.softwaremill.session.javadsl.SessionTransports.HeaderST; package com.softwaremill.session.javadsl; public class OneOffTest extends HttpSessionAwareDirectivesTest { protected Route buildRoute(HttpSessionAwareDirectives<String> testDirectives, SessionContinuity<String> oneOff, SessionContinuity<String> refreshable, SetSessionTransport sessionTransport, CsrfCheckMode<String> checkHeader) { return route( path("set", () -> testDirectives.setSession(oneOff, sessionTransport, SESSION, () -> complete("ok")) ), path("getOpt", () -> testDirectives.optionalSession(oneOff, sessionTransport, session -> complete(session.toString())) ), path("getReq", () -> testDirectives.requiredSession(oneOff, sessionTransport, session -> complete(session)) ), path("touchReq", () -> testDirectives.touchRequiredSession(oneOff, sessionTransport, session -> complete(session)) ), path("invalidate", () -> testDirectives.invalidateSession(oneOff, sessionTransport, () -> complete("ok")) ), path("full", () -> testDirectives.session(oneOff, sessionTransport, sessionResult -> complete(sessionResult.toString())) ) ); } @Test public void shouldSetTheCorrectSessionCookieName_UsingCookies() { // given
final Route route = createRoute(CookieST);
softwaremill/akka-http-session
javaTests/src/test/java/com/softwaremill/session/javadsl/OneOffTest.java
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport HeaderST = HeaderST$.MODULE$;
import akka.http.javadsl.model.HttpHeader; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.headers.Cookie; import akka.http.javadsl.model.headers.HttpCookie; import akka.http.javadsl.model.headers.RawHeader; import akka.http.javadsl.server.Route; import akka.http.javadsl.testkit.TestRouteResult; import akka.http.scaladsl.model.HttpResponse; import com.softwaremill.session.CsrfCheckMode; import com.softwaremill.session.SessionContinuity; import com.softwaremill.session.SetSessionTransport; import org.junit.Assert; import org.junit.Test; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; import static com.softwaremill.session.javadsl.SessionTransports.HeaderST;
Assert.assertNotNull(csrfCookie.value()); } @Test public void shouldSetTheSession_UsingCookies() { // given final Route route = createRoute(CookieST); // when TestRouteResult testRouteResult = testRoute(route) .run(HttpRequest.GET("/set")); // then testRouteResult .assertStatusCode(StatusCodes.OK) .assertEntity("ok"); // and HttpResponse response = testRouteResult.response(); // check _sessiondata cookie HttpCookie sessionDataCookie = getSessionDataCookieValues(response); Assert.assertTrue(sessionDataCookie.value().endsWith(URL_ENCODED_SESSION)); } @Test public void shouldSetTheSession_UsingHeaders() { // given
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport HeaderST = HeaderST$.MODULE$; // Path: javaTests/src/test/java/com/softwaremill/session/javadsl/OneOffTest.java import akka.http.javadsl.model.HttpHeader; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.headers.Cookie; import akka.http.javadsl.model.headers.HttpCookie; import akka.http.javadsl.model.headers.RawHeader; import akka.http.javadsl.server.Route; import akka.http.javadsl.testkit.TestRouteResult; import akka.http.scaladsl.model.HttpResponse; import com.softwaremill.session.CsrfCheckMode; import com.softwaremill.session.SessionContinuity; import com.softwaremill.session.SetSessionTransport; import org.junit.Assert; import org.junit.Test; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; import static com.softwaremill.session.javadsl.SessionTransports.HeaderST; Assert.assertNotNull(csrfCookie.value()); } @Test public void shouldSetTheSession_UsingCookies() { // given final Route route = createRoute(CookieST); // when TestRouteResult testRouteResult = testRoute(route) .run(HttpRequest.GET("/set")); // then testRouteResult .assertStatusCode(StatusCodes.OK) .assertEntity("ok"); // and HttpResponse response = testRouteResult.response(); // check _sessiondata cookie HttpCookie sessionDataCookie = getSessionDataCookieValues(response); Assert.assertTrue(sessionDataCookie.value().endsWith(URL_ENCODED_SESSION)); } @Test public void shouldSetTheSession_UsingHeaders() { // given
final Route route = createRoute(HeaderST);
softwaremill/akka-http-session
example/src/main/java/com/softwaremill/example/serializers/MyJavaSingleSessionSerializer.java
// Path: example/src/main/java/com/softwaremill/example/SomeJavaComplexObject.java // public class SomeJavaComplexObject { // // private final String value; // // public SomeJavaComplexObject(String value) { // this.value = value; // } // // public String getValue() { // return value; // } // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionSerializers.java // public final class SessionSerializers { // // public static final SessionSerializer<String, String> StringToStringSessionSerializer = SessionSerializer$.MODULE$.stringToStringSessionSerializer(); // public static final SessionSerializer<Integer, String> IntToStringSessionSerializer = (SessionSerializer<Integer, String>) (SessionSerializer) SessionSerializer$.MODULE$.intToStringSessionSerializer(); // public static final SessionSerializer<Long, String> LongToStringSessionSerializer = (SessionSerializer<Long, String>) (SessionSerializer) SessionSerializer$.MODULE$.longToStringSessionSerializer(); // public static final SessionSerializer<Float, String> FloatToStringSessionSerializer = (SessionSerializer<Float, String>) (SessionSerializer) SessionSerializer$.MODULE$.floatToStringSessionSerializer(); // public static final SessionSerializer<Double, String> DoubleToStringSessionSerializer = (SessionSerializer<Double, String>) (SessionSerializer) SessionSerializer$.MODULE$.doubleToStringSessionSerializer(); // // public static final SessionSerializer<Map<String, String>, String> MapToStringSessionSerializer = new MultiValueSessionSerializer<>( // (JFunction1<Map<String, String>, scala.collection.immutable.Map<String, String>>) m -> MapConverters.toImmutableMap(m), // (JFunction1<scala.collection.immutable.Map<String, String>, Try<Map<String, String>>>) v1 -> // Try.apply((JFunction0<Map<String, String>>) () -> JavaConverters.mapAsJavaMapConverter(v1).asJava()) // ); // // private SessionSerializers() { // } // // }
import com.softwaremill.example.SomeJavaComplexObject; import com.softwaremill.session.SessionSerializer; import com.softwaremill.session.SingleValueSessionSerializer; import com.softwaremill.session.javadsl.SessionSerializers; import scala.Function1; import scala.compat.java8.JFunction0; import scala.compat.java8.JFunction1; import scala.util.Try;
package com.softwaremill.example.serializers; public class MyJavaSingleSessionSerializer extends SingleValueSessionSerializer<SomeJavaComplexObject, String> { public MyJavaSingleSessionSerializer( Function1<SomeJavaComplexObject, String> toValue, Function1<String, Try<SomeJavaComplexObject>> fromValue, SessionSerializer<String, String> valueSerializer ) { super(toValue, fromValue, valueSerializer); } public static void main(String[] args) { new MyJavaSingleSessionSerializer( (JFunction1<SomeJavaComplexObject, String>) SomeJavaComplexObject::getValue, (JFunction1<String, Try<SomeJavaComplexObject>>) value -> Try.apply((JFunction0<SomeJavaComplexObject>) () -> new SomeJavaComplexObject(value)),
// Path: example/src/main/java/com/softwaremill/example/SomeJavaComplexObject.java // public class SomeJavaComplexObject { // // private final String value; // // public SomeJavaComplexObject(String value) { // this.value = value; // } // // public String getValue() { // return value; // } // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionSerializers.java // public final class SessionSerializers { // // public static final SessionSerializer<String, String> StringToStringSessionSerializer = SessionSerializer$.MODULE$.stringToStringSessionSerializer(); // public static final SessionSerializer<Integer, String> IntToStringSessionSerializer = (SessionSerializer<Integer, String>) (SessionSerializer) SessionSerializer$.MODULE$.intToStringSessionSerializer(); // public static final SessionSerializer<Long, String> LongToStringSessionSerializer = (SessionSerializer<Long, String>) (SessionSerializer) SessionSerializer$.MODULE$.longToStringSessionSerializer(); // public static final SessionSerializer<Float, String> FloatToStringSessionSerializer = (SessionSerializer<Float, String>) (SessionSerializer) SessionSerializer$.MODULE$.floatToStringSessionSerializer(); // public static final SessionSerializer<Double, String> DoubleToStringSessionSerializer = (SessionSerializer<Double, String>) (SessionSerializer) SessionSerializer$.MODULE$.doubleToStringSessionSerializer(); // // public static final SessionSerializer<Map<String, String>, String> MapToStringSessionSerializer = new MultiValueSessionSerializer<>( // (JFunction1<Map<String, String>, scala.collection.immutable.Map<String, String>>) m -> MapConverters.toImmutableMap(m), // (JFunction1<scala.collection.immutable.Map<String, String>, Try<Map<String, String>>>) v1 -> // Try.apply((JFunction0<Map<String, String>>) () -> JavaConverters.mapAsJavaMapConverter(v1).asJava()) // ); // // private SessionSerializers() { // } // // } // Path: example/src/main/java/com/softwaremill/example/serializers/MyJavaSingleSessionSerializer.java import com.softwaremill.example.SomeJavaComplexObject; import com.softwaremill.session.SessionSerializer; import com.softwaremill.session.SingleValueSessionSerializer; import com.softwaremill.session.javadsl.SessionSerializers; import scala.Function1; import scala.compat.java8.JFunction0; import scala.compat.java8.JFunction1; import scala.util.Try; package com.softwaremill.example.serializers; public class MyJavaSingleSessionSerializer extends SingleValueSessionSerializer<SomeJavaComplexObject, String> { public MyJavaSingleSessionSerializer( Function1<SomeJavaComplexObject, String> toValue, Function1<String, Try<SomeJavaComplexObject>> fromValue, SessionSerializer<String, String> valueSerializer ) { super(toValue, fromValue, valueSerializer); } public static void main(String[] args) { new MyJavaSingleSessionSerializer( (JFunction1<SomeJavaComplexObject, String>) SomeJavaComplexObject::getValue, (JFunction1<String, Try<SomeJavaComplexObject>>) value -> Try.apply((JFunction0<SomeJavaComplexObject>) () -> new SomeJavaComplexObject(value)),
SessionSerializers.StringToStringSessionSerializer
softwaremill/akka-http-session
example/src/main/java/com/softwaremill/example/session/SetSessionJava.java
// Path: core/src/main/java/com/softwaremill/session/javadsl/HttpSessionAwareDirectives.java // public class HttpSessionAwareDirectives<T> extends AllDirectives { // // private final SessionManager<T> sessionManager; // // public HttpSessionAwareDirectives(SessionManager<T> sessionManager) { // this.sessionManager = sessionManager; // } // // public Route session(SessionContinuity sc, GetSessionTransport st, Function<SessionResult<T>, Route> continuity) { // return SessionDirectives$.MODULE$.session(sc, st, continuity); // } // // public Route setSession(SessionContinuity sc, SetSessionTransport st, T session, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.setSession(sc, st, session, continuity); // } // // public Route optionalSession(SessionContinuity sc, SetSessionTransport st, Function<Optional<T>, Route> continuity) { // return SessionDirectives$.MODULE$.optionalSession(sc, st, continuity); // } // // public Route requiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.requiredSession(sc, st, continuity); // } // // public Route touchRequiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.touchRequiredSession(sc, st, continuity); // } // // public Route invalidateSession(SessionContinuity<T> sc, SetSessionTransport st, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.invalidateSession(sc, st, continuity); // } // // public Route setNewCsrfToken(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.setNewCsrfToken(checkHeader, continuity); // } // // public Route randomTokenCsrfProtection(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.randomTokenCsrfProtection(checkHeader, continuity); // } // // public SessionManager<T> getSessionManager() { // return sessionManager; // } // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$;
import akka.NotUsed; import akka.actor.ActorSystem; import akka.dispatch.MessageDispatcher; import akka.http.javadsl.ConnectHttp; import akka.http.javadsl.Http; import akka.http.javadsl.ServerBinding; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.HttpResponse; import akka.http.javadsl.server.Route; import akka.http.javadsl.unmarshalling.Unmarshaller; import akka.stream.ActorMaterializer; import akka.stream.javadsl.Flow; import com.softwaremill.session.BasicSessionEncoder; import com.softwaremill.session.CheckHeader; import com.softwaremill.session.RefreshTokenStorage; import com.softwaremill.session.Refreshable; import com.softwaremill.session.SessionConfig; import com.softwaremill.session.SessionEncoder; import com.softwaremill.session.SessionManager; import com.softwaremill.session.SetSessionTransport; import com.softwaremill.session.javadsl.HttpSessionAwareDirectives; import com.softwaremill.session.javadsl.InMemoryRefreshTokenStorage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.CompletionStage; import static com.softwaremill.session.javadsl.SessionTransports.CookieST;
package com.softwaremill.example.session; public class SetSessionJava extends HttpSessionAwareDirectives<MyJavaSession> { private static final Logger LOGGER = LoggerFactory.getLogger(SetSessionJava.class); private static final String SECRET = "c05ll3lesrinf39t7mc5h6un6r0c69lgfno69dsak3vabeqamouq4328cuaekros401ajdpkh60rrtpd8ro24rbuqmgtnd1ebag6ljnb65i8a55d482ok7o0nch0bfbe"; private static final SessionEncoder<MyJavaSession> BASIC_ENCODER = new BasicSessionEncoder<>(MyJavaSession.getSerializer()); // in-memory refresh token storage private static final RefreshTokenStorage<MyJavaSession> REFRESH_TOKEN_STORAGE = new InMemoryRefreshTokenStorage<MyJavaSession>() { @Override public void log(String msg) { LOGGER.info(msg); } }; private Refreshable<MyJavaSession> refreshable; private SetSessionTransport sessionTransport; public SetSessionJava(MessageDispatcher dispatcher) { super(new SessionManager<>( SessionConfig.defaultConfig(SECRET), BASIC_ENCODER ) ); refreshable = new Refreshable<>(getSessionManager(), REFRESH_TOKEN_STORAGE, dispatcher);
// Path: core/src/main/java/com/softwaremill/session/javadsl/HttpSessionAwareDirectives.java // public class HttpSessionAwareDirectives<T> extends AllDirectives { // // private final SessionManager<T> sessionManager; // // public HttpSessionAwareDirectives(SessionManager<T> sessionManager) { // this.sessionManager = sessionManager; // } // // public Route session(SessionContinuity sc, GetSessionTransport st, Function<SessionResult<T>, Route> continuity) { // return SessionDirectives$.MODULE$.session(sc, st, continuity); // } // // public Route setSession(SessionContinuity sc, SetSessionTransport st, T session, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.setSession(sc, st, session, continuity); // } // // public Route optionalSession(SessionContinuity sc, SetSessionTransport st, Function<Optional<T>, Route> continuity) { // return SessionDirectives$.MODULE$.optionalSession(sc, st, continuity); // } // // public Route requiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.requiredSession(sc, st, continuity); // } // // public Route touchRequiredSession(SessionContinuity<T> sc, SetSessionTransport st, Function<T, Route> continuity) { // return SessionDirectives$.MODULE$.touchRequiredSession(sc, st, continuity); // } // // public Route invalidateSession(SessionContinuity<T> sc, SetSessionTransport st, Supplier<Route> continuity) { // return SessionDirectives$.MODULE$.invalidateSession(sc, st, continuity); // } // // public Route setNewCsrfToken(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.setNewCsrfToken(checkHeader, continuity); // } // // public Route randomTokenCsrfProtection(CsrfCheckMode<T> checkHeader, Supplier<Route> continuity) { // return CsrfDirectives$.MODULE$.randomTokenCsrfProtection(checkHeader, continuity); // } // // public SessionManager<T> getSessionManager() { // return sessionManager; // } // } // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // Path: example/src/main/java/com/softwaremill/example/session/SetSessionJava.java import akka.NotUsed; import akka.actor.ActorSystem; import akka.dispatch.MessageDispatcher; import akka.http.javadsl.ConnectHttp; import akka.http.javadsl.Http; import akka.http.javadsl.ServerBinding; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.HttpResponse; import akka.http.javadsl.server.Route; import akka.http.javadsl.unmarshalling.Unmarshaller; import akka.stream.ActorMaterializer; import akka.stream.javadsl.Flow; import com.softwaremill.session.BasicSessionEncoder; import com.softwaremill.session.CheckHeader; import com.softwaremill.session.RefreshTokenStorage; import com.softwaremill.session.Refreshable; import com.softwaremill.session.SessionConfig; import com.softwaremill.session.SessionEncoder; import com.softwaremill.session.SessionManager; import com.softwaremill.session.SetSessionTransport; import com.softwaremill.session.javadsl.HttpSessionAwareDirectives; import com.softwaremill.session.javadsl.InMemoryRefreshTokenStorage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.concurrent.CompletionStage; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; package com.softwaremill.example.session; public class SetSessionJava extends HttpSessionAwareDirectives<MyJavaSession> { private static final Logger LOGGER = LoggerFactory.getLogger(SetSessionJava.class); private static final String SECRET = "c05ll3lesrinf39t7mc5h6un6r0c69lgfno69dsak3vabeqamouq4328cuaekros401ajdpkh60rrtpd8ro24rbuqmgtnd1ebag6ljnb65i8a55d482ok7o0nch0bfbe"; private static final SessionEncoder<MyJavaSession> BASIC_ENCODER = new BasicSessionEncoder<>(MyJavaSession.getSerializer()); // in-memory refresh token storage private static final RefreshTokenStorage<MyJavaSession> REFRESH_TOKEN_STORAGE = new InMemoryRefreshTokenStorage<MyJavaSession>() { @Override public void log(String msg) { LOGGER.info(msg); } }; private Refreshable<MyJavaSession> refreshable; private SetSessionTransport sessionTransport; public SetSessionJava(MessageDispatcher dispatcher) { super(new SessionManager<>( SessionConfig.defaultConfig(SECRET), BASIC_ENCODER ) ); refreshable = new Refreshable<>(getSessionManager(), REFRESH_TOKEN_STORAGE, dispatcher);
sessionTransport = CookieST;
softwaremill/akka-http-session
javaTests/src/test/java/com/softwaremill/session/javadsl/OneOffSetRefreshableGetTest.java
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport HeaderST = HeaderST$.MODULE$;
import akka.http.javadsl.model.HttpHeader; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.headers.Cookie; import akka.http.javadsl.model.headers.HttpCookie; import akka.http.javadsl.model.headers.RawHeader; import akka.http.javadsl.server.Route; import akka.http.javadsl.testkit.TestRouteResult; import akka.http.scaladsl.model.HttpResponse; import com.softwaremill.session.CsrfCheckMode; import com.softwaremill.session.SessionContinuity; import com.softwaremill.session.SetSessionTransport; import org.junit.Assert; import org.junit.Test; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; import static com.softwaremill.session.javadsl.SessionTransports.HeaderST;
package com.softwaremill.session.javadsl; public class OneOffSetRefreshableGetTest extends HttpSessionAwareDirectivesTest { protected Route buildRoute(HttpSessionAwareDirectives<String> testDirectives, SessionContinuity<String> oneOff, SessionContinuity<String> refreshable, SetSessionTransport sessionTransport, CsrfCheckMode<String> checkHeader) { return route( path("set", () -> testDirectives.setSession(oneOff, sessionTransport, SESSION, () -> complete("ok")) ), path("getOpt", () -> testDirectives.optionalSession(refreshable, sessionTransport, session -> complete(session.toString())) ), path("touchReq", () -> testDirectives.touchRequiredSession(refreshable, sessionTransport, session -> complete(session)) ), path("invalidate", () -> testDirectives.invalidateSession(refreshable, sessionTransport, () -> complete("ok")) ) ); } @Test public void shouldReadAnOptionalSessionWhenOnlyTheSessionIsSet_UsingCookies() { // given
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport HeaderST = HeaderST$.MODULE$; // Path: javaTests/src/test/java/com/softwaremill/session/javadsl/OneOffSetRefreshableGetTest.java import akka.http.javadsl.model.HttpHeader; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.headers.Cookie; import akka.http.javadsl.model.headers.HttpCookie; import akka.http.javadsl.model.headers.RawHeader; import akka.http.javadsl.server.Route; import akka.http.javadsl.testkit.TestRouteResult; import akka.http.scaladsl.model.HttpResponse; import com.softwaremill.session.CsrfCheckMode; import com.softwaremill.session.SessionContinuity; import com.softwaremill.session.SetSessionTransport; import org.junit.Assert; import org.junit.Test; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; import static com.softwaremill.session.javadsl.SessionTransports.HeaderST; package com.softwaremill.session.javadsl; public class OneOffSetRefreshableGetTest extends HttpSessionAwareDirectivesTest { protected Route buildRoute(HttpSessionAwareDirectives<String> testDirectives, SessionContinuity<String> oneOff, SessionContinuity<String> refreshable, SetSessionTransport sessionTransport, CsrfCheckMode<String> checkHeader) { return route( path("set", () -> testDirectives.setSession(oneOff, sessionTransport, SESSION, () -> complete("ok")) ), path("getOpt", () -> testDirectives.optionalSession(refreshable, sessionTransport, session -> complete(session.toString())) ), path("touchReq", () -> testDirectives.touchRequiredSession(refreshable, sessionTransport, session -> complete(session)) ), path("invalidate", () -> testDirectives.invalidateSession(refreshable, sessionTransport, () -> complete("ok")) ) ); } @Test public void shouldReadAnOptionalSessionWhenOnlyTheSessionIsSet_UsingCookies() { // given
final Route route = createRoute(CookieST);
softwaremill/akka-http-session
javaTests/src/test/java/com/softwaremill/session/javadsl/OneOffSetRefreshableGetTest.java
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport HeaderST = HeaderST$.MODULE$;
import akka.http.javadsl.model.HttpHeader; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.headers.Cookie; import akka.http.javadsl.model.headers.HttpCookie; import akka.http.javadsl.model.headers.RawHeader; import akka.http.javadsl.server.Route; import akka.http.javadsl.testkit.TestRouteResult; import akka.http.scaladsl.model.HttpResponse; import com.softwaremill.session.CsrfCheckMode; import com.softwaremill.session.SessionContinuity; import com.softwaremill.session.SetSessionTransport; import org.junit.Assert; import org.junit.Test; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; import static com.softwaremill.session.javadsl.SessionTransports.HeaderST;
testDirectives.invalidateSession(refreshable, sessionTransport, () -> complete("ok")) ) ); } @Test public void shouldReadAnOptionalSessionWhenOnlyTheSessionIsSet_UsingCookies() { // given final Route route = createRoute(CookieST); // and TestRouteResult setRouteResult = testRoute(route) .run(HttpRequest.GET("/set")); HttpCookie sessionData = getSessionDataCookieValues(setRouteResult.response()); // when TestRouteResult getOptRouteResult = testRoute(route) .run(HttpRequest.GET("/getOpt") .addHeader(Cookie.create(sessionDataCookieName, sessionData.value())) ); // then getOptRouteResult.assertStatusCode(StatusCodes.OK); getOptRouteResult.assertEntity(EXPECTED_SESSION); } @Test public void shouldReadAnOptionalSessionWhenOnlyTheSessionIsSet_UsingHeaders() { // given
// Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport CookieST = CookieST$.MODULE$; // // Path: core/src/main/java/com/softwaremill/session/javadsl/SessionTransports.java // public static final SetSessionTransport HeaderST = HeaderST$.MODULE$; // Path: javaTests/src/test/java/com/softwaremill/session/javadsl/OneOffSetRefreshableGetTest.java import akka.http.javadsl.model.HttpHeader; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.model.StatusCodes; import akka.http.javadsl.model.headers.Cookie; import akka.http.javadsl.model.headers.HttpCookie; import akka.http.javadsl.model.headers.RawHeader; import akka.http.javadsl.server.Route; import akka.http.javadsl.testkit.TestRouteResult; import akka.http.scaladsl.model.HttpResponse; import com.softwaremill.session.CsrfCheckMode; import com.softwaremill.session.SessionContinuity; import com.softwaremill.session.SetSessionTransport; import org.junit.Assert; import org.junit.Test; import static com.softwaremill.session.javadsl.SessionTransports.CookieST; import static com.softwaremill.session.javadsl.SessionTransports.HeaderST; testDirectives.invalidateSession(refreshable, sessionTransport, () -> complete("ok")) ) ); } @Test public void shouldReadAnOptionalSessionWhenOnlyTheSessionIsSet_UsingCookies() { // given final Route route = createRoute(CookieST); // and TestRouteResult setRouteResult = testRoute(route) .run(HttpRequest.GET("/set")); HttpCookie sessionData = getSessionDataCookieValues(setRouteResult.response()); // when TestRouteResult getOptRouteResult = testRoute(route) .run(HttpRequest.GET("/getOpt") .addHeader(Cookie.create(sessionDataCookieName, sessionData.value())) ); // then getOptRouteResult.assertStatusCode(StatusCodes.OK); getOptRouteResult.assertEntity(EXPECTED_SESSION); } @Test public void shouldReadAnOptionalSessionWhenOnlyTheSessionIsSet_UsingHeaders() { // given
final Route route = createRoute(HeaderST);
hdodenhof/holoreader
src/de/hdodenhof/holoreader/provider/RSSContentProvider.java
// Path: src/de/hdodenhof/holoreader/provider/SQLiteHelper.java // public class ArticleDAO { // // public static final String TABLE = "articles"; // public static final String _ID = "_id"; // public static final String FEEDID = "feedid"; // public static final String FEEDNAME = "feedname"; // public static final String GUID = "guid"; // public static final String PUBDATE = "pubdate"; // public static final String TITLE = "title"; // public static final String SUMMARY = "summary"; // public static final String CONTENT = "content"; // public static final String IMAGE = "image"; // public static final String LINK = "link"; // public static final String READ = "read"; // public static final String ISDELETED = "isdeleted"; // // public static final String VIEW = "articles_view"; // // private static final String IDX_FEEDID = "idx_article_feedid"; // // } // // Path: src/de/hdodenhof/holoreader/provider/SQLiteHelper.java // public class FeedDAO { // // public static final String TABLE = "feeds"; // public static final String _ID = "_id"; // public static final String NAME = "name"; // public static final String URL = "url"; // public static final String UPDATED = "updated"; // public static final String UNREAD = "unread"; // // public static final String VIEW = "feeds_view"; // // }
import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import de.hdodenhof.holoreader.provider.SQLiteHelper.ArticleDAO; import de.hdodenhof.holoreader.provider.SQLiteHelper.FeedDAO;
public static final Uri URI_ARTICLES = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH_ARTICLES); public static final String TYPE_FEEDS = ContentResolver.CURSOR_DIR_BASE_TYPE + "/feeds"; public static final String ITEM_TYPE_FEEDS = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/feed"; public static final String TYPE_ARTICLES = ContentResolver.CURSOR_DIR_BASE_TYPE + "/articles"; public static final String ITEM_TYPE_ARTICLES = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/article"; private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sURIMatcher.addURI(AUTHORITY, BASE_PATH_FEEDS, FEEDS); sURIMatcher.addURI(AUTHORITY, BASE_PATH_FEEDS + "/#", FEED_ID); sURIMatcher.addURI(AUTHORITY, BASE_PATH_ARTICLES, ARTICLES); sURIMatcher.addURI(AUTHORITY, BASE_PATH_ARTICLES + "/#", ARTICLE_ID); } @Override public boolean onCreate() { mSQLiteHelper = new SQLiteHelper(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); int uriType = sURIMatcher.match(uri); switch (uriType) { case FEEDS:
// Path: src/de/hdodenhof/holoreader/provider/SQLiteHelper.java // public class ArticleDAO { // // public static final String TABLE = "articles"; // public static final String _ID = "_id"; // public static final String FEEDID = "feedid"; // public static final String FEEDNAME = "feedname"; // public static final String GUID = "guid"; // public static final String PUBDATE = "pubdate"; // public static final String TITLE = "title"; // public static final String SUMMARY = "summary"; // public static final String CONTENT = "content"; // public static final String IMAGE = "image"; // public static final String LINK = "link"; // public static final String READ = "read"; // public static final String ISDELETED = "isdeleted"; // // public static final String VIEW = "articles_view"; // // private static final String IDX_FEEDID = "idx_article_feedid"; // // } // // Path: src/de/hdodenhof/holoreader/provider/SQLiteHelper.java // public class FeedDAO { // // public static final String TABLE = "feeds"; // public static final String _ID = "_id"; // public static final String NAME = "name"; // public static final String URL = "url"; // public static final String UPDATED = "updated"; // public static final String UNREAD = "unread"; // // public static final String VIEW = "feeds_view"; // // } // Path: src/de/hdodenhof/holoreader/provider/RSSContentProvider.java import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import de.hdodenhof.holoreader.provider.SQLiteHelper.ArticleDAO; import de.hdodenhof.holoreader.provider.SQLiteHelper.FeedDAO; public static final Uri URI_ARTICLES = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH_ARTICLES); public static final String TYPE_FEEDS = ContentResolver.CURSOR_DIR_BASE_TYPE + "/feeds"; public static final String ITEM_TYPE_FEEDS = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/feed"; public static final String TYPE_ARTICLES = ContentResolver.CURSOR_DIR_BASE_TYPE + "/articles"; public static final String ITEM_TYPE_ARTICLES = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/article"; private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sURIMatcher.addURI(AUTHORITY, BASE_PATH_FEEDS, FEEDS); sURIMatcher.addURI(AUTHORITY, BASE_PATH_FEEDS + "/#", FEED_ID); sURIMatcher.addURI(AUTHORITY, BASE_PATH_ARTICLES, ARTICLES); sURIMatcher.addURI(AUTHORITY, BASE_PATH_ARTICLES + "/#", ARTICLE_ID); } @Override public boolean onCreate() { mSQLiteHelper = new SQLiteHelper(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); int uriType = sURIMatcher.match(uri); switch (uriType) { case FEEDS:
queryBuilder.setTables(FeedDAO.VIEW);
hdodenhof/holoreader
src/de/hdodenhof/holoreader/provider/RSSContentProvider.java
// Path: src/de/hdodenhof/holoreader/provider/SQLiteHelper.java // public class ArticleDAO { // // public static final String TABLE = "articles"; // public static final String _ID = "_id"; // public static final String FEEDID = "feedid"; // public static final String FEEDNAME = "feedname"; // public static final String GUID = "guid"; // public static final String PUBDATE = "pubdate"; // public static final String TITLE = "title"; // public static final String SUMMARY = "summary"; // public static final String CONTENT = "content"; // public static final String IMAGE = "image"; // public static final String LINK = "link"; // public static final String READ = "read"; // public static final String ISDELETED = "isdeleted"; // // public static final String VIEW = "articles_view"; // // private static final String IDX_FEEDID = "idx_article_feedid"; // // } // // Path: src/de/hdodenhof/holoreader/provider/SQLiteHelper.java // public class FeedDAO { // // public static final String TABLE = "feeds"; // public static final String _ID = "_id"; // public static final String NAME = "name"; // public static final String URL = "url"; // public static final String UPDATED = "updated"; // public static final String UNREAD = "unread"; // // public static final String VIEW = "feeds_view"; // // }
import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import de.hdodenhof.holoreader.provider.SQLiteHelper.ArticleDAO; import de.hdodenhof.holoreader.provider.SQLiteHelper.FeedDAO;
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sURIMatcher.addURI(AUTHORITY, BASE_PATH_FEEDS, FEEDS); sURIMatcher.addURI(AUTHORITY, BASE_PATH_FEEDS + "/#", FEED_ID); sURIMatcher.addURI(AUTHORITY, BASE_PATH_ARTICLES, ARTICLES); sURIMatcher.addURI(AUTHORITY, BASE_PATH_ARTICLES + "/#", ARTICLE_ID); } @Override public boolean onCreate() { mSQLiteHelper = new SQLiteHelper(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); int uriType = sURIMatcher.match(uri); switch (uriType) { case FEEDS: queryBuilder.setTables(FeedDAO.VIEW); break; case FEED_ID: queryBuilder.setTables(FeedDAO.VIEW); queryBuilder.appendWhere(FeedDAO._ID + "=" + uri.getLastPathSegment()); break; case ARTICLES:
// Path: src/de/hdodenhof/holoreader/provider/SQLiteHelper.java // public class ArticleDAO { // // public static final String TABLE = "articles"; // public static final String _ID = "_id"; // public static final String FEEDID = "feedid"; // public static final String FEEDNAME = "feedname"; // public static final String GUID = "guid"; // public static final String PUBDATE = "pubdate"; // public static final String TITLE = "title"; // public static final String SUMMARY = "summary"; // public static final String CONTENT = "content"; // public static final String IMAGE = "image"; // public static final String LINK = "link"; // public static final String READ = "read"; // public static final String ISDELETED = "isdeleted"; // // public static final String VIEW = "articles_view"; // // private static final String IDX_FEEDID = "idx_article_feedid"; // // } // // Path: src/de/hdodenhof/holoreader/provider/SQLiteHelper.java // public class FeedDAO { // // public static final String TABLE = "feeds"; // public static final String _ID = "_id"; // public static final String NAME = "name"; // public static final String URL = "url"; // public static final String UPDATED = "updated"; // public static final String UNREAD = "unread"; // // public static final String VIEW = "feeds_view"; // // } // Path: src/de/hdodenhof/holoreader/provider/RSSContentProvider.java import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import de.hdodenhof.holoreader.provider.SQLiteHelper.ArticleDAO; import de.hdodenhof.holoreader.provider.SQLiteHelper.FeedDAO; private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sURIMatcher.addURI(AUTHORITY, BASE_PATH_FEEDS, FEEDS); sURIMatcher.addURI(AUTHORITY, BASE_PATH_FEEDS + "/#", FEED_ID); sURIMatcher.addURI(AUTHORITY, BASE_PATH_ARTICLES, ARTICLES); sURIMatcher.addURI(AUTHORITY, BASE_PATH_ARTICLES + "/#", ARTICLE_ID); } @Override public boolean onCreate() { mSQLiteHelper = new SQLiteHelper(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); int uriType = sURIMatcher.match(uri); switch (uriType) { case FEEDS: queryBuilder.setTables(FeedDAO.VIEW); break; case FEED_ID: queryBuilder.setTables(FeedDAO.VIEW); queryBuilder.appendWhere(FeedDAO._ID + "=" + uri.getLastPathSegment()); break; case ARTICLES:
queryBuilder.setTables(ArticleDAO.VIEW);
hdodenhof/holoreader
src/de/hdodenhof/holoreader/gcm/GCMServerUtilities.java
// Path: src/de/hdodenhof/holoreader/Config.java // public class Config { // // public static final String API_BASEURL = "https://holoreader.appspot.com/api/"; // public static final String GCM_SENDER_ID = ""; // // }
import java.net.URI; import java.util.HashMap; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.CoreConnectionPNames; import com.google.gson.Gson; import de.hdodenhof.holoreader.Config;
package de.hdodenhof.holoreader.gcm; public class GCMServerUtilities { @SuppressWarnings("unused") private static final String TAG = GCMServerUtilities.class.getName(); public static boolean registerOnServer(String eMail, String regId, String uuid) { try { HashMap<String, String> entityMap = new HashMap<String, String>(); entityMap.put("eMail", eMail); entityMap.put("regId", regId); entityMap.put("uuid", uuid); entityMap.put("device", android.os.Build.MODEL); String entity = new Gson().toJson(entityMap); HttpPut request = new HttpPut();
// Path: src/de/hdodenhof/holoreader/Config.java // public class Config { // // public static final String API_BASEURL = "https://holoreader.appspot.com/api/"; // public static final String GCM_SENDER_ID = ""; // // } // Path: src/de/hdodenhof/holoreader/gcm/GCMServerUtilities.java import java.net.URI; import java.util.HashMap; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.CoreConnectionPNames; import com.google.gson.Gson; import de.hdodenhof.holoreader.Config; package de.hdodenhof.holoreader.gcm; public class GCMServerUtilities { @SuppressWarnings("unused") private static final String TAG = GCMServerUtilities.class.getName(); public static boolean registerOnServer(String eMail, String regId, String uuid) { try { HashMap<String, String> entityMap = new HashMap<String, String>(); entityMap.put("eMail", eMail); entityMap.put("regId", regId); entityMap.put("uuid", uuid); entityMap.put("device", android.os.Build.MODEL); String entity = new Gson().toJson(entityMap); HttpPut request = new HttpPut();
request.setURI(new URI(Config.API_BASEURL + "register"));
hdodenhof/holoreader
src/de/hdodenhof/holoreader/listadapters/EditFeedAdapter.java
// Path: src/de/hdodenhof/holoreader/provider/SQLiteHelper.java // public class FeedDAO { // // public static final String TABLE = "feeds"; // public static final String _ID = "_id"; // public static final String NAME = "name"; // public static final String URL = "url"; // public static final String UPDATED = "updated"; // public static final String UNREAD = "unread"; // // public static final String VIEW = "feeds_view"; // // }
import android.content.Context; import android.database.Cursor; import android.support.v4.widget.SimpleCursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import de.hdodenhof.holoreader.R; import de.hdodenhof.holoreader.provider.SQLiteHelper.FeedDAO;
package de.hdodenhof.holoreader.listadapters; /** * * @author Henning Dodenhof * */ public class EditFeedAdapter extends SimpleCursorAdapter { @SuppressWarnings("unused") private static final String TAG = EditFeedAdapter.class.getSimpleName(); private int mLayout; public EditFeedAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) { super(context, layout, c, from, to, flags); mLayout = layout; } @Override public void bindView(View view, Context context, Cursor cursor) {
// Path: src/de/hdodenhof/holoreader/provider/SQLiteHelper.java // public class FeedDAO { // // public static final String TABLE = "feeds"; // public static final String _ID = "_id"; // public static final String NAME = "name"; // public static final String URL = "url"; // public static final String UPDATED = "updated"; // public static final String UNREAD = "unread"; // // public static final String VIEW = "feeds_view"; // // } // Path: src/de/hdodenhof/holoreader/listadapters/EditFeedAdapter.java import android.content.Context; import android.database.Cursor; import android.support.v4.widget.SimpleCursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import de.hdodenhof.holoreader.R; import de.hdodenhof.holoreader.provider.SQLiteHelper.FeedDAO; package de.hdodenhof.holoreader.listadapters; /** * * @author Henning Dodenhof * */ public class EditFeedAdapter extends SimpleCursorAdapter { @SuppressWarnings("unused") private static final String TAG = EditFeedAdapter.class.getSimpleName(); private int mLayout; public EditFeedAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) { super(context, layout, c, from, to, flags); mLayout = layout; } @Override public void bindView(View view, Context context, Cursor cursor) {
String name = cursor.getString(cursor.getColumnIndex(FeedDAO.NAME));
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/DockerRuleBuilder.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidVolumeFrom.java // public class InvalidVolumeFrom extends IllegalStateException { // // public InvalidVolumeFrom(String message) { // super(message); // } // // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/StartCondition.java // public interface StartCondition { // /** // * Create {@link StartConditionCheck} instances for current {@link DockerRule}. // */ // StartConditionCheck build(DockerRule currentRule); // }
import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.spotify.docker.client.messages.HostConfig; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.junit.rules.RuleChain; import com.spotify.docker.client.messages.PortBinding; import pl.domzal.junit.docker.rule.ex.InvalidVolumeFrom; import pl.domzal.junit.docker.rule.wait.StartCondition;
package pl.domzal.junit.docker.rule; public class DockerRuleBuilder { static final int WAIT_FOR_DEFAULT_SECONDS = 30; private String imageName; private String name; private List<String> binds = new ArrayList<>(); private List<String> env = new ArrayList<>(); private List<String> staticLinks = new ArrayList<>(); private List<Pair<DockerRule,String>> dynamicLinks = new ArrayList<>(); private Map<String,String> labels = new HashMap<>(); private List<HostConfig.Ulimit> ulimits = new ArrayList<>(); private ExposePortBindingBuilder exposeBuilder = ExposePortBindingBuilder.builder(); private boolean publishAllPorts = true; private String[] entrypoint; private String[] cmd; private String[] extraHosts; private boolean imageAlwaysPull = false; private PrintStream stdoutWriter; private PrintStream stderrWriter;
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidVolumeFrom.java // public class InvalidVolumeFrom extends IllegalStateException { // // public InvalidVolumeFrom(String message) { // super(message); // } // // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/StartCondition.java // public interface StartCondition { // /** // * Create {@link StartConditionCheck} instances for current {@link DockerRule}. // */ // StartConditionCheck build(DockerRule currentRule); // } // Path: src/main/java/pl/domzal/junit/docker/rule/DockerRuleBuilder.java import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.spotify.docker.client.messages.HostConfig; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.junit.rules.RuleChain; import com.spotify.docker.client.messages.PortBinding; import pl.domzal.junit.docker.rule.ex.InvalidVolumeFrom; import pl.domzal.junit.docker.rule.wait.StartCondition; package pl.domzal.junit.docker.rule; public class DockerRuleBuilder { static final int WAIT_FOR_DEFAULT_SECONDS = 30; private String imageName; private String name; private List<String> binds = new ArrayList<>(); private List<String> env = new ArrayList<>(); private List<String> staticLinks = new ArrayList<>(); private List<Pair<DockerRule,String>> dynamicLinks = new ArrayList<>(); private Map<String,String> labels = new HashMap<>(); private List<HostConfig.Ulimit> ulimits = new ArrayList<>(); private ExposePortBindingBuilder exposeBuilder = ExposePortBindingBuilder.builder(); private boolean publishAllPorts = true; private String[] entrypoint; private String[] cmd; private String[] extraHosts; private boolean imageAlwaysPull = false; private PrintStream stdoutWriter; private PrintStream stderrWriter;
private List<StartCondition> waitConditions = new ArrayList<>();
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/DockerRuleBuilder.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidVolumeFrom.java // public class InvalidVolumeFrom extends IllegalStateException { // // public InvalidVolumeFrom(String message) { // super(message); // } // // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/StartCondition.java // public interface StartCondition { // /** // * Create {@link StartConditionCheck} instances for current {@link DockerRule}. // */ // StartConditionCheck build(DockerRule currentRule); // }
import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.spotify.docker.client.messages.HostConfig; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.junit.rules.RuleChain; import com.spotify.docker.client.messages.PortBinding; import pl.domzal.junit.docker.rule.ex.InvalidVolumeFrom; import pl.domzal.junit.docker.rule.wait.StartCondition;
* @deprecated Use {@link #stopOptions(StopOption...)} instead. */ public DockerRuleBuilder keepContainer(boolean keepContainer) { if (keepContainer) { this.stopOptions.setOptions(StopOption.KEEP); } else { this.stopOptions.setOptions(StopOption.REMOVE); } return this; } /** * Force image pull even when image is already present. */ public DockerRuleBuilder imageAlwaysPull(boolean alwaysPull) { this.imageAlwaysPull = alwaysPull; return this; } boolean imageAlwaysPull() { return imageAlwaysPull; } /** * Docker volume OR host directory to be mounted into container.<br/> * Please note that in case of host folder and boot2docker environments (OSX or Windows) * only locations inside $HOME can work (/Users or /c/Users respectively).<br/> * On Windows it is safer to use {@link #mountFrom(File)} instead. * * @param volumeOrPath Docker volume OR directory/file to be mounted (must be specified Unix style). */
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidVolumeFrom.java // public class InvalidVolumeFrom extends IllegalStateException { // // public InvalidVolumeFrom(String message) { // super(message); // } // // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/StartCondition.java // public interface StartCondition { // /** // * Create {@link StartConditionCheck} instances for current {@link DockerRule}. // */ // StartConditionCheck build(DockerRule currentRule); // } // Path: src/main/java/pl/domzal/junit/docker/rule/DockerRuleBuilder.java import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.spotify.docker.client.messages.HostConfig; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.junit.rules.RuleChain; import com.spotify.docker.client.messages.PortBinding; import pl.domzal.junit.docker.rule.ex.InvalidVolumeFrom; import pl.domzal.junit.docker.rule.wait.StartCondition; * @deprecated Use {@link #stopOptions(StopOption...)} instead. */ public DockerRuleBuilder keepContainer(boolean keepContainer) { if (keepContainer) { this.stopOptions.setOptions(StopOption.KEEP); } else { this.stopOptions.setOptions(StopOption.REMOVE); } return this; } /** * Force image pull even when image is already present. */ public DockerRuleBuilder imageAlwaysPull(boolean alwaysPull) { this.imageAlwaysPull = alwaysPull; return this; } boolean imageAlwaysPull() { return imageAlwaysPull; } /** * Docker volume OR host directory to be mounted into container.<br/> * Please note that in case of host folder and boot2docker environments (OSX or Windows) * only locations inside $HOME can work (/Users or /c/Users respectively).<br/> * On Windows it is safer to use {@link #mountFrom(File)} instead. * * @param volumeOrPath Docker volume OR directory/file to be mounted (must be specified Unix style). */
public DockerRuleMountToBuilder mountFrom(String volumeOrPath) throws InvalidVolumeFrom {
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/ExposePortBindingBuilder.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidPortDefinition.java // public class InvalidPortDefinition extends IllegalStateException { // // public InvalidPortDefinition(String port) { // super("Invalid port: "+port); // } // // }
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang3.StringUtils; import com.google.common.collect.Lists; import com.spotify.docker.client.messages.HostConfig; import com.spotify.docker.client.messages.PortBinding; import pl.domzal.junit.docker.rule.ex.InvalidPortDefinition;
assertValidContainerPort(containerPort); assertHostPortNotAssigned(hostPort); addBinding(Ports.portWithProtocol(containerPort), PortBinding.of(BIND_ALL, hostPort)); return this; } public ExposePortBindingBuilder expose(String containerPort) { assertValidContainerPort(containerPort); addBinding(Ports.portWithProtocol(containerPort), PortBinding.randomPort(BIND_ALL)); return this; } private void addBinding(String containerBind, PortBinding hostBind) { if (bindings.containsKey(containerBind)) { bindings.get(containerBind).add(hostBind); } else { bindings.put(containerBind, Lists.newArrayList(hostBind)); } } Map<String, List<PortBinding>> hostBindings() { return bindings; } Set<String> containerExposedPorts() { return bindings.keySet(); } private void assertIsNumber(String portToCheck) { if ( ! StringUtils.isNumeric(portToCheck) ) {
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidPortDefinition.java // public class InvalidPortDefinition extends IllegalStateException { // // public InvalidPortDefinition(String port) { // super("Invalid port: "+port); // } // // } // Path: src/main/java/pl/domzal/junit/docker/rule/ExposePortBindingBuilder.java import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang3.StringUtils; import com.google.common.collect.Lists; import com.spotify.docker.client.messages.HostConfig; import com.spotify.docker.client.messages.PortBinding; import pl.domzal.junit.docker.rule.ex.InvalidPortDefinition; assertValidContainerPort(containerPort); assertHostPortNotAssigned(hostPort); addBinding(Ports.portWithProtocol(containerPort), PortBinding.of(BIND_ALL, hostPort)); return this; } public ExposePortBindingBuilder expose(String containerPort) { assertValidContainerPort(containerPort); addBinding(Ports.portWithProtocol(containerPort), PortBinding.randomPort(BIND_ALL)); return this; } private void addBinding(String containerBind, PortBinding hostBind) { if (bindings.containsKey(containerBind)) { bindings.get(containerBind).add(hostBind); } else { bindings.put(containerBind, Lists.newArrayList(hostBind)); } } Map<String, List<PortBinding>> hostBindings() { return bindings; } Set<String> containerExposedPorts() { return bindings.keySet(); } private void assertIsNumber(String portToCheck) { if ( ! StringUtils.isNumeric(portToCheck) ) {
throw new InvalidPortDefinition(portToCheck);
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/LinkNameValidator.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidParameter.java // public class InvalidParameter extends IllegalStateException { // // public InvalidParameter(String message) { // super(message); // } // // }
import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import pl.domzal.junit.docker.rule.ex.InvalidParameter;
package pl.domzal.junit.docker.rule; class LinkNameValidator { private static final String VALID_NAME_REGEX = "[a-zA-Z0-9_-]+"; private static final String VALID_LINK_DEFINITION_REGEX = "[a-zA-Z0-9_-]+(:[a-zA-Z0-9_-]+)?"; private static Pattern NAME_PATTERN = Pattern.compile(VALID_NAME_REGEX); private static Pattern LINK_PATTERN = Pattern.compile(VALID_LINK_DEFINITION_REGEX); public static String validateContainerName(String name) { if (StringUtils.isBlank(name)) {
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidParameter.java // public class InvalidParameter extends IllegalStateException { // // public InvalidParameter(String message) { // super(message); // } // // } // Path: src/main/java/pl/domzal/junit/docker/rule/LinkNameValidator.java import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import pl.domzal.junit.docker.rule.ex.InvalidParameter; package pl.domzal.junit.docker.rule; class LinkNameValidator { private static final String VALID_NAME_REGEX = "[a-zA-Z0-9_-]+"; private static final String VALID_LINK_DEFINITION_REGEX = "[a-zA-Z0-9_-]+(:[a-zA-Z0-9_-]+)?"; private static Pattern NAME_PATTERN = Pattern.compile(VALID_NAME_REGEX); private static Pattern LINK_PATTERN = Pattern.compile(VALID_LINK_DEFINITION_REGEX); public static String validateContainerName(String name) { if (StringUtils.isBlank(name)) {
throw new InvalidParameter("Name definition is empty");
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/logs/LogPrinter.java
// Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // }
import java.io.InputStream; import java.io.PrintStream; import java.util.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.domzal.junit.docker.rule.wait.LineListener;
package pl.domzal.junit.docker.rule.logs; public class LogPrinter implements Runnable { private static Logger log = LoggerFactory.getLogger(LogPrinter.class); private final String prefix; private final InputStream scannedInputStream; private final PrintStream output;
// Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // } // Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogPrinter.java import java.io.InputStream; import java.io.PrintStream; import java.util.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.domzal.junit.docker.rule.wait.LineListener; package pl.domzal.junit.docker.rule.logs; public class LogPrinter implements Runnable { private static Logger log = LoggerFactory.getLogger(LogPrinter.class); private final String prefix; private final InputStream scannedInputStream; private final PrintStream output;
private final LineListener lineListener;
tdomzal/junit-docker-rule
src/test/java/pl/domzal/junit/docker/rule/LinkValidatorTest.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidParameter.java // public class InvalidParameter extends IllegalStateException { // // public InvalidParameter(String message) { // super(message); // } // // }
import org.junit.Test; import org.junit.experimental.categories.Category; import pl.domzal.junit.docker.rule.ex.InvalidParameter;
package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class LinkValidatorTest {
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidParameter.java // public class InvalidParameter extends IllegalStateException { // // public InvalidParameter(String message) { // super(message); // } // // } // Path: src/test/java/pl/domzal/junit/docker/rule/LinkValidatorTest.java import org.junit.Test; import org.junit.experimental.categories.Category; import pl.domzal.junit.docker.rule.ex.InvalidParameter; package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class LinkValidatorTest {
@Test(expected = InvalidParameter.class)
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/WaitUtil.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/WaitTimeoutException.java // public class WaitTimeoutException extends TimeoutException { // // private final long waited; // // public WaitTimeoutException(String message, long waited) { // super(message); // this.waited = waited; // } // // public long getWaited() { // return waited; // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/StartConditionCheck.java // public interface StartConditionCheck { // // /** // * 'Is condition fulfilled?' check. // */ // boolean check(); // // /** // * Condition description (will show in log messages). // */ // String describe(); // // /** // * After check cleanup. Use if you check need to do some cleaning after usage. // */ // void after(); // // }
import java.util.Arrays; import pl.domzal.junit.docker.rule.ex.WaitTimeoutException; import pl.domzal.junit.docker.rule.wait.StartConditionCheck;
package pl.domzal.junit.docker.rule; public class WaitUtil { // how long to wait at max when doing a http ping private static final long DEFAULT_MAX_WAIT = 10 * 1000; // How long to wait between pings private static final long WAIT_RETRY_WAIT = 500; private WaitUtil() {}
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/WaitTimeoutException.java // public class WaitTimeoutException extends TimeoutException { // // private final long waited; // // public WaitTimeoutException(String message, long waited) { // super(message); // this.waited = waited; // } // // public long getWaited() { // return waited; // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/StartConditionCheck.java // public interface StartConditionCheck { // // /** // * 'Is condition fulfilled?' check. // */ // boolean check(); // // /** // * Condition description (will show in log messages). // */ // String describe(); // // /** // * After check cleanup. Use if you check need to do some cleaning after usage. // */ // void after(); // // } // Path: src/main/java/pl/domzal/junit/docker/rule/WaitUtil.java import java.util.Arrays; import pl.domzal.junit.docker.rule.ex.WaitTimeoutException; import pl.domzal.junit.docker.rule.wait.StartConditionCheck; package pl.domzal.junit.docker.rule; public class WaitUtil { // how long to wait at max when doing a http ping private static final long DEFAULT_MAX_WAIT = 10 * 1000; // How long to wait between pings private static final long WAIT_RETRY_WAIT = 500; private WaitUtil() {}
public static long wait(int maxWait, StartConditionCheck... checkers) throws WaitTimeoutException {
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/WaitUtil.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/WaitTimeoutException.java // public class WaitTimeoutException extends TimeoutException { // // private final long waited; // // public WaitTimeoutException(String message, long waited) { // super(message); // this.waited = waited; // } // // public long getWaited() { // return waited; // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/StartConditionCheck.java // public interface StartConditionCheck { // // /** // * 'Is condition fulfilled?' check. // */ // boolean check(); // // /** // * Condition description (will show in log messages). // */ // String describe(); // // /** // * After check cleanup. Use if you check need to do some cleaning after usage. // */ // void after(); // // }
import java.util.Arrays; import pl.domzal.junit.docker.rule.ex.WaitTimeoutException; import pl.domzal.junit.docker.rule.wait.StartConditionCheck;
package pl.domzal.junit.docker.rule; public class WaitUtil { // how long to wait at max when doing a http ping private static final long DEFAULT_MAX_WAIT = 10 * 1000; // How long to wait between pings private static final long WAIT_RETRY_WAIT = 500; private WaitUtil() {}
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/WaitTimeoutException.java // public class WaitTimeoutException extends TimeoutException { // // private final long waited; // // public WaitTimeoutException(String message, long waited) { // super(message); // this.waited = waited; // } // // public long getWaited() { // return waited; // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/StartConditionCheck.java // public interface StartConditionCheck { // // /** // * 'Is condition fulfilled?' check. // */ // boolean check(); // // /** // * Condition description (will show in log messages). // */ // String describe(); // // /** // * After check cleanup. Use if you check need to do some cleaning after usage. // */ // void after(); // // } // Path: src/main/java/pl/domzal/junit/docker/rule/WaitUtil.java import java.util.Arrays; import pl.domzal.junit.docker.rule.ex.WaitTimeoutException; import pl.domzal.junit.docker.rule.wait.StartConditionCheck; package pl.domzal.junit.docker.rule; public class WaitUtil { // how long to wait at max when doing a http ping private static final long DEFAULT_MAX_WAIT = 10 * 1000; // How long to wait between pings private static final long WAIT_RETRY_WAIT = 500; private WaitUtil() {}
public static long wait(int maxWait, StartConditionCheck... checkers) throws WaitTimeoutException {
tdomzal/junit-docker-rule
src/test/java/pl/domzal/junit/docker/rule/DockerRuleVolumeMountTest.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidVolumeFrom.java // public class InvalidVolumeFrom extends IllegalStateException { // // public InvalidVolumeFrom(String message) { // super(message); // } // // }
import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TemporaryFolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.LogsParam; import com.spotify.docker.client.LogStream; import pl.domzal.junit.docker.rule.ex.InvalidVolumeFrom;
testFilename = testFile.getName(); try (Writer out = new FileWriter(testFile)) { IOUtils.write(testFileContent, out); } testDir = tempFolder.getRoot(); log.debug("testDir: {}", testDir.getAbsolutePath()); testDirPath = DockerRuleMountBuilder.toUnixStylePath(testDir.getAbsolutePath()); log.debug("testDirPath: {}", testDirPath); } private DockerRule testee; @After public void tearDown() { // make sure testee will bee cleaned up after test cases // commit tear down is more convienient than 'try {} finally in every test case' if (testee != null) { testee.after(); } } @Test public void shouldFailWhenMountFromDoesNotExist() { try { File nonexistingHostDir = testDir.toPath().resolve("nonexisting").toFile(); log.debug("mountFrom: "+nonexistingHostDir.getAbsolutePath()); testee = DockerRule.builder()// .imageName("busybox:1.25.1")// .mountFrom(nonexistingHostDir).to("/somedir", "ro")// .build();
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidVolumeFrom.java // public class InvalidVolumeFrom extends IllegalStateException { // // public InvalidVolumeFrom(String message) { // super(message); // } // // } // Path: src/test/java/pl/domzal/junit/docker/rule/DockerRuleVolumeMountTest.java import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TemporaryFolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.LogsParam; import com.spotify.docker.client.LogStream; import pl.domzal.junit.docker.rule.ex.InvalidVolumeFrom; testFilename = testFile.getName(); try (Writer out = new FileWriter(testFile)) { IOUtils.write(testFileContent, out); } testDir = tempFolder.getRoot(); log.debug("testDir: {}", testDir.getAbsolutePath()); testDirPath = DockerRuleMountBuilder.toUnixStylePath(testDir.getAbsolutePath()); log.debug("testDirPath: {}", testDirPath); } private DockerRule testee; @After public void tearDown() { // make sure testee will bee cleaned up after test cases // commit tear down is more convienient than 'try {} finally in every test case' if (testee != null) { testee.after(); } } @Test public void shouldFailWhenMountFromDoesNotExist() { try { File nonexistingHostDir = testDir.toPath().resolve("nonexisting").toFile(); log.debug("mountFrom: "+nonexistingHostDir.getAbsolutePath()); testee = DockerRule.builder()// .imageName("busybox:1.25.1")// .mountFrom(nonexistingHostDir).to("/somedir", "ro")// .build();
fail("should fail with "+InvalidVolumeFrom.class.getSimpleName());
tdomzal/junit-docker-rule
src/test/java/pl/domzal/junit/docker/rule/logs/LogSplitterTest.java
// Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // }
import static org.mockito.Mockito.*; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.domzal.junit.docker.rule.wait.LineListener;
package pl.domzal.junit.docker.rule.logs; public class LogSplitterTest { private static Logger log = LoggerFactory.getLogger(LogSplitterTest.class); public static final int NO_OF_LOG_LISTENERS = 3; private final ExecutorService executor = Executors.newFixedThreadPool(NO_OF_LOG_LISTENERS);
// Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // } // Path: src/test/java/pl/domzal/junit/docker/rule/logs/LogSplitterTest.java import static org.mockito.Mockito.*; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.domzal.junit.docker.rule.wait.LineListener; package pl.domzal.junit.docker.rule.logs; public class LogSplitterTest { private static Logger log = LoggerFactory.getLogger(LogSplitterTest.class); public static final int NO_OF_LOG_LISTENERS = 3; private final ExecutorService executor = Executors.newFixedThreadPool(NO_OF_LOG_LISTENERS);
private LineListener combinedLines = mock(LineListener.class);
tdomzal/junit-docker-rule
src/test/java/pl/domzal/junit/docker/rule/DockerRuleMountBuilderTest.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidVolumeFrom.java // public class InvalidVolumeFrom extends IllegalStateException { // // public InvalidVolumeFrom(String message) { // super(message); // } // // }
import static org.junit.Assert.*; import java.util.Map; import org.apache.commons.lang3.SystemUtils; import org.junit.Test; import org.junit.experimental.categories.Category; import pl.domzal.junit.docker.rule.ex.InvalidVolumeFrom;
package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class DockerRuleMountBuilderTest { @Test public void shouldAcceptValidDockerVolume() throws Exception { DockerRuleMountBuilder.assertValidMountFrom("/Users/someuser", "abcdef", true, false); } @Test public void shouldAcceptOsxHomePath() throws Exception { DockerRuleMountBuilder.assertValidMountFrom("/Users/someuser", "/Users/someuser/temp", true, false); }
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidVolumeFrom.java // public class InvalidVolumeFrom extends IllegalStateException { // // public InvalidVolumeFrom(String message) { // super(message); // } // // } // Path: src/test/java/pl/domzal/junit/docker/rule/DockerRuleMountBuilderTest.java import static org.junit.Assert.*; import java.util.Map; import org.apache.commons.lang3.SystemUtils; import org.junit.Test; import org.junit.experimental.categories.Category; import pl.domzal.junit.docker.rule.ex.InvalidVolumeFrom; package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class DockerRuleMountBuilderTest { @Test public void shouldAcceptValidDockerVolume() throws Exception { DockerRuleMountBuilder.assertValidMountFrom("/Users/someuser", "abcdef", true, false); } @Test public void shouldAcceptOsxHomePath() throws Exception { DockerRuleMountBuilder.assertValidMountFrom("/Users/someuser", "/Users/someuser/temp", true, false); }
@Test(expected = InvalidVolumeFrom.class)
tdomzal/junit-docker-rule
src/test/java/pl/domzal/junit/docker/rule/DockerRuleWaitForPortTest.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/PortNotExposedException.java // public class PortNotExposedException extends IllegalStateException { // // public PortNotExposedException(String port) { // super(port); // } // // }
import static org.junit.Assert.*; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.domzal.junit.docker.rule.ex.PortNotExposedException;
package pl.domzal.junit.docker.rule; @Category(test.category.TcpPorts.class) public class DockerRuleWaitForPortTest { private static Logger log = LoggerFactory.getLogger(DockerRuleWaitForPortTest.class);
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/PortNotExposedException.java // public class PortNotExposedException extends IllegalStateException { // // public PortNotExposedException(String port) { // super(port); // } // // } // Path: src/test/java/pl/domzal/junit/docker/rule/DockerRuleWaitForPortTest.java import static org.junit.Assert.*; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.domzal.junit.docker.rule.ex.PortNotExposedException; package pl.domzal.junit.docker.rule; @Category(test.category.TcpPorts.class) public class DockerRuleWaitForPortTest { private static Logger log = LoggerFactory.getLogger(DockerRuleWaitForPortTest.class);
@Test(expected = PortNotExposedException.class)
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/Ports.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidPortDefinition.java // public class InvalidPortDefinition extends IllegalStateException { // // public InvalidPortDefinition(String port) { // super("Invalid port: "+port); // } // // }
import org.apache.commons.lang3.StringUtils; import pl.domzal.junit.docker.rule.ex.InvalidPortDefinition;
package pl.domzal.junit.docker.rule; class Ports { public static final String TCP_PORT_SUFFIX = "/tcp"; public static final String UDP_PORT_SUFFIX = "/udp"; public static final int PORT_SUFFIX_LENGTH = 4; /** * Prepare port definition ready for binding.<p/> * Example (input -&gt; ouput): * <pre> * "80" -> "80/tcp" * "80/tcp" -> "80/tcp" * "80/udp" -> "80/udp" * </pre> */ public static String portWithProtocol(String port) { if (isPortWithProtocol(port)) { return port; } else if (StringUtils.isNumeric(port)) { return port + "/tcp"; } else {
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidPortDefinition.java // public class InvalidPortDefinition extends IllegalStateException { // // public InvalidPortDefinition(String port) { // super("Invalid port: "+port); // } // // } // Path: src/main/java/pl/domzal/junit/docker/rule/Ports.java import org.apache.commons.lang3.StringUtils; import pl.domzal.junit.docker.rule.ex.InvalidPortDefinition; package pl.domzal.junit.docker.rule; class Ports { public static final String TCP_PORT_SUFFIX = "/tcp"; public static final String UDP_PORT_SUFFIX = "/udp"; public static final int PORT_SUFFIX_LENGTH = 4; /** * Prepare port definition ready for binding.<p/> * Example (input -&gt; ouput): * <pre> * "80" -> "80/tcp" * "80/tcp" -> "80/tcp" * "80/udp" -> "80/udp" * </pre> */ public static String portWithProtocol(String port) { if (isPortWithProtocol(port)) { return port; } else if (StringUtils.isNumeric(port)) { return port + "/tcp"; } else {
throw new InvalidPortDefinition(port);
tdomzal/junit-docker-rule
src/test/java/pl/domzal/junit/docker/rule/WaitForContainerTest.java
// Path: src/main/java/pl/domzal/junit/docker/rule/wait/StartConditionCheck.java // public interface StartConditionCheck { // // /** // * 'Is condition fulfilled?' check. // */ // boolean check(); // // /** // * Condition description (will show in log messages). // */ // String describe(); // // /** // * After check cleanup. Use if you check need to do some cleaning after usage. // */ // void after(); // // }
import static org.mockito.Mockito.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import junit.framework.AssertionFailedError; import pl.domzal.junit.docker.rule.wait.StartConditionCheck;
package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class WaitForContainerTest { private static Logger log = LoggerFactory.getLogger(WaitForContainerTest.class); public static final int WAIT_LOG_TIMEOUT_SEC = 4; private final ExecutorService executor = Executors.newSingleThreadExecutor(); private final AtomicBoolean doneWaiting = new AtomicBoolean(false); private final AtomicBoolean timeoutWaiting = new AtomicBoolean(false); private final AtomicReference<Throwable> exceptionWaiting = new AtomicReference<>(); class WaitRunner implements Runnable {
// Path: src/main/java/pl/domzal/junit/docker/rule/wait/StartConditionCheck.java // public interface StartConditionCheck { // // /** // * 'Is condition fulfilled?' check. // */ // boolean check(); // // /** // * Condition description (will show in log messages). // */ // String describe(); // // /** // * After check cleanup. Use if you check need to do some cleaning after usage. // */ // void after(); // // } // Path: src/test/java/pl/domzal/junit/docker/rule/WaitForContainerTest.java import static org.mockito.Mockito.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import junit.framework.AssertionFailedError; import pl.domzal.junit.docker.rule.wait.StartConditionCheck; package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class WaitForContainerTest { private static Logger log = LoggerFactory.getLogger(WaitForContainerTest.class); public static final int WAIT_LOG_TIMEOUT_SEC = 4; private final ExecutorService executor = Executors.newSingleThreadExecutor(); private final AtomicBoolean doneWaiting = new AtomicBoolean(false); private final AtomicBoolean timeoutWaiting = new AtomicBoolean(false); private final AtomicReference<Throwable> exceptionWaiting = new AtomicReference<>(); class WaitRunner implements Runnable {
private final StartConditionCheck condition;
tdomzal/junit-docker-rule
src/test/java/pl/domzal/junit/docker/rule/DockerLogsLogPrinterTest.java
// Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogPrinter.java // public class LogPrinter implements Runnable { // // private static Logger log = LoggerFactory.getLogger(LogPrinter.class); // // private final String prefix; // private final InputStream scannedInputStream; // private final PrintStream output; // private final LineListener lineListener; // // public LogPrinter(String prefix, InputStream scannedInputStream, PrintStream output, LineListener lineListener) { // this.prefix = prefix; // this.scannedInputStream = scannedInputStream; // this.output = output; // this.lineListener = lineListener; // } // // @Override // public void run() { // log.trace("{} printer thread started", prefix); // try (Scanner scanner = new Scanner(scannedInputStream)) { // while (scanner.hasNextLine()) { // String line = scanner.nextLine(); // log.trace("{} line: {}", prefix, line); // if (output != null) { // output.println(prefix + line); // } // if (lineListener != null) { // lineListener.nextLine(line); // } // } // } // log.trace("{} printer thread terminated", prefix); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // }
import static org.mockito.Mockito.*; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.InOrder; import pl.domzal.junit.docker.rule.logs.LogPrinter; import pl.domzal.junit.docker.rule.wait.LineListener;
package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class DockerLogsLogPrinterTest { private final ExecutorService executor = Executors.newSingleThreadExecutor(); private PrintWriter containerStdout; private ByteArrayOutputStream logOutputStream;
// Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogPrinter.java // public class LogPrinter implements Runnable { // // private static Logger log = LoggerFactory.getLogger(LogPrinter.class); // // private final String prefix; // private final InputStream scannedInputStream; // private final PrintStream output; // private final LineListener lineListener; // // public LogPrinter(String prefix, InputStream scannedInputStream, PrintStream output, LineListener lineListener) { // this.prefix = prefix; // this.scannedInputStream = scannedInputStream; // this.output = output; // this.lineListener = lineListener; // } // // @Override // public void run() { // log.trace("{} printer thread started", prefix); // try (Scanner scanner = new Scanner(scannedInputStream)) { // while (scanner.hasNextLine()) { // String line = scanner.nextLine(); // log.trace("{} line: {}", prefix, line); // if (output != null) { // output.println(prefix + line); // } // if (lineListener != null) { // lineListener.nextLine(line); // } // } // } // log.trace("{} printer thread terminated", prefix); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // } // Path: src/test/java/pl/domzal/junit/docker/rule/DockerLogsLogPrinterTest.java import static org.mockito.Mockito.*; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.InOrder; import pl.domzal.junit.docker.rule.logs.LogPrinter; import pl.domzal.junit.docker.rule.wait.LineListener; package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class DockerLogsLogPrinterTest { private final ExecutorService executor = Executors.newSingleThreadExecutor(); private PrintWriter containerStdout; private ByteArrayOutputStream logOutputStream;
LineListener lineListener = mock(LineListener.class);
tdomzal/junit-docker-rule
src/test/java/pl/domzal/junit/docker/rule/DockerLogsLogPrinterTest.java
// Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogPrinter.java // public class LogPrinter implements Runnable { // // private static Logger log = LoggerFactory.getLogger(LogPrinter.class); // // private final String prefix; // private final InputStream scannedInputStream; // private final PrintStream output; // private final LineListener lineListener; // // public LogPrinter(String prefix, InputStream scannedInputStream, PrintStream output, LineListener lineListener) { // this.prefix = prefix; // this.scannedInputStream = scannedInputStream; // this.output = output; // this.lineListener = lineListener; // } // // @Override // public void run() { // log.trace("{} printer thread started", prefix); // try (Scanner scanner = new Scanner(scannedInputStream)) { // while (scanner.hasNextLine()) { // String line = scanner.nextLine(); // log.trace("{} line: {}", prefix, line); // if (output != null) { // output.println(prefix + line); // } // if (lineListener != null) { // lineListener.nextLine(line); // } // } // } // log.trace("{} printer thread terminated", prefix); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // }
import static org.mockito.Mockito.*; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.InOrder; import pl.domzal.junit.docker.rule.logs.LogPrinter; import pl.domzal.junit.docker.rule.wait.LineListener;
package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class DockerLogsLogPrinterTest { private final ExecutorService executor = Executors.newSingleThreadExecutor(); private PrintWriter containerStdout; private ByteArrayOutputStream logOutputStream; LineListener lineListener = mock(LineListener.class);
// Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogPrinter.java // public class LogPrinter implements Runnable { // // private static Logger log = LoggerFactory.getLogger(LogPrinter.class); // // private final String prefix; // private final InputStream scannedInputStream; // private final PrintStream output; // private final LineListener lineListener; // // public LogPrinter(String prefix, InputStream scannedInputStream, PrintStream output, LineListener lineListener) { // this.prefix = prefix; // this.scannedInputStream = scannedInputStream; // this.output = output; // this.lineListener = lineListener; // } // // @Override // public void run() { // log.trace("{} printer thread started", prefix); // try (Scanner scanner = new Scanner(scannedInputStream)) { // while (scanner.hasNextLine()) { // String line = scanner.nextLine(); // log.trace("{} line: {}", prefix, line); // if (output != null) { // output.println(prefix + line); // } // if (lineListener != null) { // lineListener.nextLine(line); // } // } // } // log.trace("{} printer thread terminated", prefix); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // } // Path: src/test/java/pl/domzal/junit/docker/rule/DockerLogsLogPrinterTest.java import static org.mockito.Mockito.*; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.InOrder; import pl.domzal.junit.docker.rule.logs.LogPrinter; import pl.domzal.junit.docker.rule.wait.LineListener; package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class DockerLogsLogPrinterTest { private final ExecutorService executor = Executors.newSingleThreadExecutor(); private PrintWriter containerStdout; private ByteArrayOutputStream logOutputStream; LineListener lineListener = mock(LineListener.class);
LogPrinter testee;
tdomzal/junit-docker-rule
src/test/java/pl/domzal/junit/docker/rule/NameValidatorTest.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidParameter.java // public class InvalidParameter extends IllegalStateException { // // public InvalidParameter(String message) { // super(message); // } // // }
import org.junit.Test; import org.junit.experimental.categories.Category; import pl.domzal.junit.docker.rule.ex.InvalidParameter;
package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class NameValidatorTest {
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidParameter.java // public class InvalidParameter extends IllegalStateException { // // public InvalidParameter(String message) { // super(message); // } // // } // Path: src/test/java/pl/domzal/junit/docker/rule/NameValidatorTest.java import org.junit.Test; import org.junit.experimental.categories.Category; import pl.domzal.junit.docker.rule.ex.InvalidParameter; package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class NameValidatorTest {
@Test(expected = InvalidParameter.class)
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/WaitForContainer.java
// Path: src/main/java/pl/domzal/junit/docker/rule/wait/StartConditionCheck.java // public interface StartConditionCheck { // // /** // * 'Is condition fulfilled?' check. // */ // boolean check(); // // /** // * Condition description (will show in log messages). // */ // String describe(); // // /** // * After check cleanup. Use if you check need to do some cleaning after usage. // */ // void after(); // // }
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.domzal.junit.docker.rule.wait.StartConditionCheck;
package pl.domzal.junit.docker.rule; /** * Helper class to block on given {@link WaitForContainer}. */ class WaitForContainer { private static Logger log = LoggerFactory.getLogger(WaitForContainer.class); /** * Wait till all given conditions are met. * * @param condition Conditions to wait for - all must be met to continue. * @param timeoutSeconds Wait timeout. * @param containerDescription Container description. For log and exception message usage only. */
// Path: src/main/java/pl/domzal/junit/docker/rule/wait/StartConditionCheck.java // public interface StartConditionCheck { // // /** // * 'Is condition fulfilled?' check. // */ // boolean check(); // // /** // * Condition description (will show in log messages). // */ // String describe(); // // /** // * After check cleanup. Use if you check need to do some cleaning after usage. // */ // void after(); // // } // Path: src/main/java/pl/domzal/junit/docker/rule/WaitForContainer.java import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.domzal.junit.docker.rule.wait.StartConditionCheck; package pl.domzal.junit.docker.rule; /** * Helper class to block on given {@link WaitForContainer}. */ class WaitForContainer { private static Logger log = LoggerFactory.getLogger(WaitForContainer.class); /** * Wait till all given conditions are met. * * @param condition Conditions to wait for - all must be met to continue. * @param timeoutSeconds Wait timeout. * @param containerDescription Container description. For log and exception message usage only. */
static void waitForCondition(final StartConditionCheck condition, int timeoutSeconds, final String containerDescription) throws TimeoutException {
tdomzal/junit-docker-rule
src/test/java/pl/domzal/junit/docker/rule/DockerRuleImagePullTest.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/ImagePullException.java // public class ImagePullException extends IllegalStateException { // // public ImagePullException(String message, Throwable cause) { // super(message, cause); // } // // }
import static org.junit.Assert.*; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.ListContainersParam; import com.spotify.docker.client.DockerClient.ListImagesParam; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.exceptions.ImageNotFoundException; import com.spotify.docker.client.messages.Container; import com.spotify.docker.client.messages.ContainerInfo; import com.spotify.docker.client.messages.Image; import pl.domzal.junit.docker.rule.ex.ImagePullException;
package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class DockerRuleImagePullTest { private static Logger log = LoggerFactory.getLogger(DockerRuleImagePullTest.class); @Rule public DockerRule helperRule = DockerRule.builder()// .imageName("busybox:1.25.1")// .build(); private DockerClient helperClient = helperRule.getDockerClient();
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/ImagePullException.java // public class ImagePullException extends IllegalStateException { // // public ImagePullException(String message, Throwable cause) { // super(message, cause); // } // // } // Path: src/test/java/pl/domzal/junit/docker/rule/DockerRuleImagePullTest.java import static org.junit.Assert.*; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.ListContainersParam; import com.spotify.docker.client.DockerClient.ListImagesParam; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.exceptions.ImageNotFoundException; import com.spotify.docker.client.messages.Container; import com.spotify.docker.client.messages.ContainerInfo; import com.spotify.docker.client.messages.Image; import pl.domzal.junit.docker.rule.ex.ImagePullException; package pl.domzal.junit.docker.rule; @Category(test.category.Stable.class) public class DockerRuleImagePullTest { private static Logger log = LoggerFactory.getLogger(DockerRuleImagePullTest.class); @Rule public DockerRule helperRule = DockerRule.builder()// .imageName("busybox:1.25.1")// .build(); private DockerClient helperClient = helperRule.getDockerClient();
@Test(expected = ImagePullException.class)
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/DockerRuleMountBuilder.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidVolumeFrom.java // public class InvalidVolumeFrom extends IllegalStateException { // // public InvalidVolumeFrom(String message) { // super(message); // } // // }
import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.domzal.junit.docker.rule.ex.InvalidVolumeFrom;
package pl.domzal.junit.docker.rule; class DockerRuleMountBuilder implements DockerRuleMountToBuilder { private static Logger log = LoggerFactory.getLogger(DockerRuleMountBuilder.class); private static final String OSX_HOME = "/Users"; private static final String WIN_HOME_WIN_STYLE = "C:\\Users"; private static final String WIN_HOME_UNIX_STYLE = "/c/Users"; private DockerRuleBuilder parentBuilder; private String from; private String to; private String mode;
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidVolumeFrom.java // public class InvalidVolumeFrom extends IllegalStateException { // // public InvalidVolumeFrom(String message) { // super(message); // } // // } // Path: src/main/java/pl/domzal/junit/docker/rule/DockerRuleMountBuilder.java import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.domzal.junit.docker.rule.ex.InvalidVolumeFrom; package pl.domzal.junit.docker.rule; class DockerRuleMountBuilder implements DockerRuleMountToBuilder { private static Logger log = LoggerFactory.getLogger(DockerRuleMountBuilder.class); private static final String OSX_HOME = "/Users"; private static final String WIN_HOME_WIN_STYLE = "C:\\Users"; private static final String WIN_HOME_UNIX_STYLE = "/c/Users"; private DockerRuleBuilder parentBuilder; private String from; private String to; private String mode;
DockerRuleMountBuilder(DockerRuleBuilder parentBuilder, String fromPathUnixStyle) throws InvalidVolumeFrom {
tdomzal/junit-docker-rule
src/test/java/pl/domzal/junit/docker/rule/ExposePortBindingBuilderTest.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidPortDefinition.java // public class InvalidPortDefinition extends IllegalStateException { // // public InvalidPortDefinition(String port) { // super("Invalid port: "+port); // } // // }
import static org.junit.Assert.*; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; import org.junit.experimental.categories.Category; import com.spotify.docker.client.messages.PortBinding; import pl.domzal.junit.docker.rule.ex.InvalidPortDefinition;
} @Test public void shouldMergeTwoTcpPorts() { //when builder.expose("8181", "80").expose("7171", "80"); Set<String> containerExposedPorts = builder.containerExposedPorts(); Map<String, List<PortBinding>> hostBindings = builder.hostBindings(); //then assertEquals(1, containerExposedPorts.size()); assertTrue(containerExposedPorts.contains("80/tcp")); assertEquals(1, hostBindings.size()); assertTrue(hostBindings.containsKey("80/tcp")); // 80 bind List<PortBinding> binds80 = hostBindings.get("80/tcp"); assertEquals(2, binds80.size()); assertEquals(PortBinding.of(BIND_ALL, 8181), binds80.get(0)); assertEquals(PortBinding.of(BIND_ALL, 7171), binds80.get(1)); } @Test(expected=IllegalStateException.class) public void shouldFailOnHostPortExposeDuplicated() { builder.expose("8080", "70").expose("8080", "70"); } public void shouldNotFailWhenExposedSamePortDifferentProtocols() { builder.expose("8080", "70").expose("8080", "70/udp"); }
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/InvalidPortDefinition.java // public class InvalidPortDefinition extends IllegalStateException { // // public InvalidPortDefinition(String port) { // super("Invalid port: "+port); // } // // } // Path: src/test/java/pl/domzal/junit/docker/rule/ExposePortBindingBuilderTest.java import static org.junit.Assert.*; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; import org.junit.experimental.categories.Category; import com.spotify.docker.client.messages.PortBinding; import pl.domzal.junit.docker.rule.ex.InvalidPortDefinition; } @Test public void shouldMergeTwoTcpPorts() { //when builder.expose("8181", "80").expose("7171", "80"); Set<String> containerExposedPorts = builder.containerExposedPorts(); Map<String, List<PortBinding>> hostBindings = builder.hostBindings(); //then assertEquals(1, containerExposedPorts.size()); assertTrue(containerExposedPorts.contains("80/tcp")); assertEquals(1, hostBindings.size()); assertTrue(hostBindings.containsKey("80/tcp")); // 80 bind List<PortBinding> binds80 = hostBindings.get("80/tcp"); assertEquals(2, binds80.size()); assertEquals(PortBinding.of(BIND_ALL, 8181), binds80.get(0)); assertEquals(PortBinding.of(BIND_ALL, 7171), binds80.get(1)); } @Test(expected=IllegalStateException.class) public void shouldFailOnHostPortExposeDuplicated() { builder.expose("8080", "70").expose("8080", "70"); } public void shouldNotFailWhenExposedSamePortDifferentProtocols() { builder.expose("8080", "70").expose("8080", "70/udp"); }
@Test(expected=InvalidPortDefinition.class)
tdomzal/junit-docker-rule
src/test/java/pl/domzal/junit/docker/rule/DockerRuleWaitForHttpTest.java
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/PortNotExposedException.java // public class PortNotExposedException extends IllegalStateException { // // public PortNotExposedException(String port) { // super(port); // } // // }
import static org.junit.Assert.*; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.domzal.junit.docker.rule.ex.PortNotExposedException;
package pl.domzal.junit.docker.rule; @Category(test.category.Unstable.class) public class DockerRuleWaitForHttpTest { private static Logger log = LoggerFactory.getLogger(DockerRuleWaitForHttpTest.class);
// Path: src/main/java/pl/domzal/junit/docker/rule/ex/PortNotExposedException.java // public class PortNotExposedException extends IllegalStateException { // // public PortNotExposedException(String port) { // super(port); // } // // } // Path: src/test/java/pl/domzal/junit/docker/rule/DockerRuleWaitForHttpTest.java import static org.junit.Assert.*; import org.junit.Test; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.domzal.junit.docker.rule.ex.PortNotExposedException; package pl.domzal.junit.docker.rule; @Category(test.category.Unstable.class) public class DockerRuleWaitForHttpTest { private static Logger log = LoggerFactory.getLogger(DockerRuleWaitForHttpTest.class);
@Test(expected = PortNotExposedException.class)
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/DockerLogs.java
// Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogPrinter.java // public class LogPrinter implements Runnable { // // private static Logger log = LoggerFactory.getLogger(LogPrinter.class); // // private final String prefix; // private final InputStream scannedInputStream; // private final PrintStream output; // private final LineListener lineListener; // // public LogPrinter(String prefix, InputStream scannedInputStream, PrintStream output, LineListener lineListener) { // this.prefix = prefix; // this.scannedInputStream = scannedInputStream; // this.output = output; // this.lineListener = lineListener; // } // // @Override // public void run() { // log.trace("{} printer thread started", prefix); // try (Scanner scanner = new Scanner(scannedInputStream)) { // while (scanner.hasNextLine()) { // String line = scanner.nextLine(); // log.trace("{} line: {}", prefix, line); // if (output != null) { // output.println(prefix + line); // } // if (lineListener != null) { // lineListener.nextLine(line); // } // } // } // log.trace("{} printer thread terminated", prefix); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogSplitter.java // public class LogSplitter implements Closeable { // // private final PipedInputStream stdoutInput = new PipedInputStream(); // private final PipedInputStream stderrInput = new PipedInputStream(); // private final PipedInputStream combinedInput = new PipedInputStream(); // // private final PipedOutputStream stdoutPipeOutputStream; // private final PipedOutputStream stderrPipeOutputStream; // private final PipedOutputStream combinedPipeOutputStream; // // private final OutputStream stdoutOutput; // private final OutputStream stderrOutput; // // public LogSplitter() { // try { // this.stdoutPipeOutputStream = new PipedOutputStream(stdoutInput); // this.stderrPipeOutputStream = new PipedOutputStream(stderrInput); // this.combinedPipeOutputStream = new PipedOutputStream(combinedInput); // this.stdoutOutput = new TeeOutputStream(stdoutPipeOutputStream, combinedPipeOutputStream); // this.stderrOutput = new TeeOutputStream(stderrPipeOutputStream, combinedPipeOutputStream); // } catch (IOException e) { // throw new RuntimeException("Unable to create", e); // } // } // // public OutputStream getStdoutOutput() { // return stdoutOutput; // } // // public OutputStream getStderrOutput() { // return stderrOutput; // } // // public InputStream getStdoutInput() { // return stdoutInput; // } // // public InputStream getStderrInput() { // return stderrInput; // } // // public InputStream getCombinedInput() { // return combinedInput; // } // // @Override // public void close() throws IOException { // IOUtils.closeQuietly(stderrInput); // IOUtils.closeQuietly(stdoutInput); // IOUtils.closeQuietly(combinedInput); // IOUtils.closeQuietly(stdoutPipeOutputStream); // IOUtils.closeQuietly(stderrPipeOutputStream); // IOUtils.closeQuietly(combinedPipeOutputStream); // IOUtils.closeQuietly(stdoutOutput); // IOUtils.closeQuietly(stderrOutput); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // }
import java.io.Closeable; import java.io.IOException; import java.io.PrintStream; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.LogsParam; import com.spotify.docker.client.LogStream; import pl.domzal.junit.docker.rule.logs.LogPrinter; import pl.domzal.junit.docker.rule.logs.LogSplitter; import pl.domzal.junit.docker.rule.wait.LineListener;
package pl.domzal.junit.docker.rule; /** * Docker container log binding feature. */ class DockerLogs implements Closeable { private static Logger log = LoggerFactory.getLogger(DockerLogs.class); private static final int NO_OF_THREADS = 4; private static final int SHORT_ID_LEN = 12; private final DockerClient dockerClient; private final String containerId;
// Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogPrinter.java // public class LogPrinter implements Runnable { // // private static Logger log = LoggerFactory.getLogger(LogPrinter.class); // // private final String prefix; // private final InputStream scannedInputStream; // private final PrintStream output; // private final LineListener lineListener; // // public LogPrinter(String prefix, InputStream scannedInputStream, PrintStream output, LineListener lineListener) { // this.prefix = prefix; // this.scannedInputStream = scannedInputStream; // this.output = output; // this.lineListener = lineListener; // } // // @Override // public void run() { // log.trace("{} printer thread started", prefix); // try (Scanner scanner = new Scanner(scannedInputStream)) { // while (scanner.hasNextLine()) { // String line = scanner.nextLine(); // log.trace("{} line: {}", prefix, line); // if (output != null) { // output.println(prefix + line); // } // if (lineListener != null) { // lineListener.nextLine(line); // } // } // } // log.trace("{} printer thread terminated", prefix); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogSplitter.java // public class LogSplitter implements Closeable { // // private final PipedInputStream stdoutInput = new PipedInputStream(); // private final PipedInputStream stderrInput = new PipedInputStream(); // private final PipedInputStream combinedInput = new PipedInputStream(); // // private final PipedOutputStream stdoutPipeOutputStream; // private final PipedOutputStream stderrPipeOutputStream; // private final PipedOutputStream combinedPipeOutputStream; // // private final OutputStream stdoutOutput; // private final OutputStream stderrOutput; // // public LogSplitter() { // try { // this.stdoutPipeOutputStream = new PipedOutputStream(stdoutInput); // this.stderrPipeOutputStream = new PipedOutputStream(stderrInput); // this.combinedPipeOutputStream = new PipedOutputStream(combinedInput); // this.stdoutOutput = new TeeOutputStream(stdoutPipeOutputStream, combinedPipeOutputStream); // this.stderrOutput = new TeeOutputStream(stderrPipeOutputStream, combinedPipeOutputStream); // } catch (IOException e) { // throw new RuntimeException("Unable to create", e); // } // } // // public OutputStream getStdoutOutput() { // return stdoutOutput; // } // // public OutputStream getStderrOutput() { // return stderrOutput; // } // // public InputStream getStdoutInput() { // return stdoutInput; // } // // public InputStream getStderrInput() { // return stderrInput; // } // // public InputStream getCombinedInput() { // return combinedInput; // } // // @Override // public void close() throws IOException { // IOUtils.closeQuietly(stderrInput); // IOUtils.closeQuietly(stdoutInput); // IOUtils.closeQuietly(combinedInput); // IOUtils.closeQuietly(stdoutPipeOutputStream); // IOUtils.closeQuietly(stderrPipeOutputStream); // IOUtils.closeQuietly(combinedPipeOutputStream); // IOUtils.closeQuietly(stdoutOutput); // IOUtils.closeQuietly(stderrOutput); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // } // Path: src/main/java/pl/domzal/junit/docker/rule/DockerLogs.java import java.io.Closeable; import java.io.IOException; import java.io.PrintStream; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.LogsParam; import com.spotify.docker.client.LogStream; import pl.domzal.junit.docker.rule.logs.LogPrinter; import pl.domzal.junit.docker.rule.logs.LogSplitter; import pl.domzal.junit.docker.rule.wait.LineListener; package pl.domzal.junit.docker.rule; /** * Docker container log binding feature. */ class DockerLogs implements Closeable { private static Logger log = LoggerFactory.getLogger(DockerLogs.class); private static final int NO_OF_THREADS = 4; private static final int SHORT_ID_LEN = 12; private final DockerClient dockerClient; private final String containerId;
private final LineListener lineListener;
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/DockerLogs.java
// Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogPrinter.java // public class LogPrinter implements Runnable { // // private static Logger log = LoggerFactory.getLogger(LogPrinter.class); // // private final String prefix; // private final InputStream scannedInputStream; // private final PrintStream output; // private final LineListener lineListener; // // public LogPrinter(String prefix, InputStream scannedInputStream, PrintStream output, LineListener lineListener) { // this.prefix = prefix; // this.scannedInputStream = scannedInputStream; // this.output = output; // this.lineListener = lineListener; // } // // @Override // public void run() { // log.trace("{} printer thread started", prefix); // try (Scanner scanner = new Scanner(scannedInputStream)) { // while (scanner.hasNextLine()) { // String line = scanner.nextLine(); // log.trace("{} line: {}", prefix, line); // if (output != null) { // output.println(prefix + line); // } // if (lineListener != null) { // lineListener.nextLine(line); // } // } // } // log.trace("{} printer thread terminated", prefix); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogSplitter.java // public class LogSplitter implements Closeable { // // private final PipedInputStream stdoutInput = new PipedInputStream(); // private final PipedInputStream stderrInput = new PipedInputStream(); // private final PipedInputStream combinedInput = new PipedInputStream(); // // private final PipedOutputStream stdoutPipeOutputStream; // private final PipedOutputStream stderrPipeOutputStream; // private final PipedOutputStream combinedPipeOutputStream; // // private final OutputStream stdoutOutput; // private final OutputStream stderrOutput; // // public LogSplitter() { // try { // this.stdoutPipeOutputStream = new PipedOutputStream(stdoutInput); // this.stderrPipeOutputStream = new PipedOutputStream(stderrInput); // this.combinedPipeOutputStream = new PipedOutputStream(combinedInput); // this.stdoutOutput = new TeeOutputStream(stdoutPipeOutputStream, combinedPipeOutputStream); // this.stderrOutput = new TeeOutputStream(stderrPipeOutputStream, combinedPipeOutputStream); // } catch (IOException e) { // throw new RuntimeException("Unable to create", e); // } // } // // public OutputStream getStdoutOutput() { // return stdoutOutput; // } // // public OutputStream getStderrOutput() { // return stderrOutput; // } // // public InputStream getStdoutInput() { // return stdoutInput; // } // // public InputStream getStderrInput() { // return stderrInput; // } // // public InputStream getCombinedInput() { // return combinedInput; // } // // @Override // public void close() throws IOException { // IOUtils.closeQuietly(stderrInput); // IOUtils.closeQuietly(stdoutInput); // IOUtils.closeQuietly(combinedInput); // IOUtils.closeQuietly(stdoutPipeOutputStream); // IOUtils.closeQuietly(stderrPipeOutputStream); // IOUtils.closeQuietly(combinedPipeOutputStream); // IOUtils.closeQuietly(stdoutOutput); // IOUtils.closeQuietly(stderrOutput); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // }
import java.io.Closeable; import java.io.IOException; import java.io.PrintStream; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.LogsParam; import com.spotify.docker.client.LogStream; import pl.domzal.junit.docker.rule.logs.LogPrinter; import pl.domzal.junit.docker.rule.logs.LogSplitter; import pl.domzal.junit.docker.rule.wait.LineListener;
package pl.domzal.junit.docker.rule; /** * Docker container log binding feature. */ class DockerLogs implements Closeable { private static Logger log = LoggerFactory.getLogger(DockerLogs.class); private static final int NO_OF_THREADS = 4; private static final int SHORT_ID_LEN = 12; private final DockerClient dockerClient; private final String containerId; private final LineListener lineListener; private PrintStream stdoutWriter = System.out; private PrintStream stderrWriter = System.err; private final ThreadFactory threadFactory = new ThreadFactoryBuilder()// .setNameFormat("dockerlog-pool-%d")// .setDaemon(true)// .build(); private final ExecutorService executor = Executors.newFixedThreadPool(NO_OF_THREADS, threadFactory); DockerLogs(DockerClient dockerClient, String containerId, LineListener lineListener) { this.dockerClient = dockerClient; this.containerId = containerId; this.lineListener = lineListener; } void setStderrWriter(PrintStream stderrWriter) { this.stderrWriter = stderrWriter; } void setStdoutWriter(PrintStream stdoutWriter) { this.stdoutWriter = stdoutWriter; } public void start() throws IOException, InterruptedException { final String containerShortId = StringUtils.left(containerId, SHORT_ID_LEN);
// Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogPrinter.java // public class LogPrinter implements Runnable { // // private static Logger log = LoggerFactory.getLogger(LogPrinter.class); // // private final String prefix; // private final InputStream scannedInputStream; // private final PrintStream output; // private final LineListener lineListener; // // public LogPrinter(String prefix, InputStream scannedInputStream, PrintStream output, LineListener lineListener) { // this.prefix = prefix; // this.scannedInputStream = scannedInputStream; // this.output = output; // this.lineListener = lineListener; // } // // @Override // public void run() { // log.trace("{} printer thread started", prefix); // try (Scanner scanner = new Scanner(scannedInputStream)) { // while (scanner.hasNextLine()) { // String line = scanner.nextLine(); // log.trace("{} line: {}", prefix, line); // if (output != null) { // output.println(prefix + line); // } // if (lineListener != null) { // lineListener.nextLine(line); // } // } // } // log.trace("{} printer thread terminated", prefix); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogSplitter.java // public class LogSplitter implements Closeable { // // private final PipedInputStream stdoutInput = new PipedInputStream(); // private final PipedInputStream stderrInput = new PipedInputStream(); // private final PipedInputStream combinedInput = new PipedInputStream(); // // private final PipedOutputStream stdoutPipeOutputStream; // private final PipedOutputStream stderrPipeOutputStream; // private final PipedOutputStream combinedPipeOutputStream; // // private final OutputStream stdoutOutput; // private final OutputStream stderrOutput; // // public LogSplitter() { // try { // this.stdoutPipeOutputStream = new PipedOutputStream(stdoutInput); // this.stderrPipeOutputStream = new PipedOutputStream(stderrInput); // this.combinedPipeOutputStream = new PipedOutputStream(combinedInput); // this.stdoutOutput = new TeeOutputStream(stdoutPipeOutputStream, combinedPipeOutputStream); // this.stderrOutput = new TeeOutputStream(stderrPipeOutputStream, combinedPipeOutputStream); // } catch (IOException e) { // throw new RuntimeException("Unable to create", e); // } // } // // public OutputStream getStdoutOutput() { // return stdoutOutput; // } // // public OutputStream getStderrOutput() { // return stderrOutput; // } // // public InputStream getStdoutInput() { // return stdoutInput; // } // // public InputStream getStderrInput() { // return stderrInput; // } // // public InputStream getCombinedInput() { // return combinedInput; // } // // @Override // public void close() throws IOException { // IOUtils.closeQuietly(stderrInput); // IOUtils.closeQuietly(stdoutInput); // IOUtils.closeQuietly(combinedInput); // IOUtils.closeQuietly(stdoutPipeOutputStream); // IOUtils.closeQuietly(stderrPipeOutputStream); // IOUtils.closeQuietly(combinedPipeOutputStream); // IOUtils.closeQuietly(stdoutOutput); // IOUtils.closeQuietly(stderrOutput); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // } // Path: src/main/java/pl/domzal/junit/docker/rule/DockerLogs.java import java.io.Closeable; import java.io.IOException; import java.io.PrintStream; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.LogsParam; import com.spotify.docker.client.LogStream; import pl.domzal.junit.docker.rule.logs.LogPrinter; import pl.domzal.junit.docker.rule.logs.LogSplitter; import pl.domzal.junit.docker.rule.wait.LineListener; package pl.domzal.junit.docker.rule; /** * Docker container log binding feature. */ class DockerLogs implements Closeable { private static Logger log = LoggerFactory.getLogger(DockerLogs.class); private static final int NO_OF_THREADS = 4; private static final int SHORT_ID_LEN = 12; private final DockerClient dockerClient; private final String containerId; private final LineListener lineListener; private PrintStream stdoutWriter = System.out; private PrintStream stderrWriter = System.err; private final ThreadFactory threadFactory = new ThreadFactoryBuilder()// .setNameFormat("dockerlog-pool-%d")// .setDaemon(true)// .build(); private final ExecutorService executor = Executors.newFixedThreadPool(NO_OF_THREADS, threadFactory); DockerLogs(DockerClient dockerClient, String containerId, LineListener lineListener) { this.dockerClient = dockerClient; this.containerId = containerId; this.lineListener = lineListener; } void setStderrWriter(PrintStream stderrWriter) { this.stderrWriter = stderrWriter; } void setStdoutWriter(PrintStream stdoutWriter) { this.stdoutWriter = stdoutWriter; } public void start() throws IOException, InterruptedException { final String containerShortId = StringUtils.left(containerId, SHORT_ID_LEN);
final LogSplitter logSplitter = new LogSplitter();
tdomzal/junit-docker-rule
src/main/java/pl/domzal/junit/docker/rule/DockerLogs.java
// Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogPrinter.java // public class LogPrinter implements Runnable { // // private static Logger log = LoggerFactory.getLogger(LogPrinter.class); // // private final String prefix; // private final InputStream scannedInputStream; // private final PrintStream output; // private final LineListener lineListener; // // public LogPrinter(String prefix, InputStream scannedInputStream, PrintStream output, LineListener lineListener) { // this.prefix = prefix; // this.scannedInputStream = scannedInputStream; // this.output = output; // this.lineListener = lineListener; // } // // @Override // public void run() { // log.trace("{} printer thread started", prefix); // try (Scanner scanner = new Scanner(scannedInputStream)) { // while (scanner.hasNextLine()) { // String line = scanner.nextLine(); // log.trace("{} line: {}", prefix, line); // if (output != null) { // output.println(prefix + line); // } // if (lineListener != null) { // lineListener.nextLine(line); // } // } // } // log.trace("{} printer thread terminated", prefix); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogSplitter.java // public class LogSplitter implements Closeable { // // private final PipedInputStream stdoutInput = new PipedInputStream(); // private final PipedInputStream stderrInput = new PipedInputStream(); // private final PipedInputStream combinedInput = new PipedInputStream(); // // private final PipedOutputStream stdoutPipeOutputStream; // private final PipedOutputStream stderrPipeOutputStream; // private final PipedOutputStream combinedPipeOutputStream; // // private final OutputStream stdoutOutput; // private final OutputStream stderrOutput; // // public LogSplitter() { // try { // this.stdoutPipeOutputStream = new PipedOutputStream(stdoutInput); // this.stderrPipeOutputStream = new PipedOutputStream(stderrInput); // this.combinedPipeOutputStream = new PipedOutputStream(combinedInput); // this.stdoutOutput = new TeeOutputStream(stdoutPipeOutputStream, combinedPipeOutputStream); // this.stderrOutput = new TeeOutputStream(stderrPipeOutputStream, combinedPipeOutputStream); // } catch (IOException e) { // throw new RuntimeException("Unable to create", e); // } // } // // public OutputStream getStdoutOutput() { // return stdoutOutput; // } // // public OutputStream getStderrOutput() { // return stderrOutput; // } // // public InputStream getStdoutInput() { // return stdoutInput; // } // // public InputStream getStderrInput() { // return stderrInput; // } // // public InputStream getCombinedInput() { // return combinedInput; // } // // @Override // public void close() throws IOException { // IOUtils.closeQuietly(stderrInput); // IOUtils.closeQuietly(stdoutInput); // IOUtils.closeQuietly(combinedInput); // IOUtils.closeQuietly(stdoutPipeOutputStream); // IOUtils.closeQuietly(stderrPipeOutputStream); // IOUtils.closeQuietly(combinedPipeOutputStream); // IOUtils.closeQuietly(stdoutOutput); // IOUtils.closeQuietly(stderrOutput); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // }
import java.io.Closeable; import java.io.IOException; import java.io.PrintStream; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.LogsParam; import com.spotify.docker.client.LogStream; import pl.domzal.junit.docker.rule.logs.LogPrinter; import pl.domzal.junit.docker.rule.logs.LogSplitter; import pl.domzal.junit.docker.rule.wait.LineListener;
package pl.domzal.junit.docker.rule; /** * Docker container log binding feature. */ class DockerLogs implements Closeable { private static Logger log = LoggerFactory.getLogger(DockerLogs.class); private static final int NO_OF_THREADS = 4; private static final int SHORT_ID_LEN = 12; private final DockerClient dockerClient; private final String containerId; private final LineListener lineListener; private PrintStream stdoutWriter = System.out; private PrintStream stderrWriter = System.err; private final ThreadFactory threadFactory = new ThreadFactoryBuilder()// .setNameFormat("dockerlog-pool-%d")// .setDaemon(true)// .build(); private final ExecutorService executor = Executors.newFixedThreadPool(NO_OF_THREADS, threadFactory); DockerLogs(DockerClient dockerClient, String containerId, LineListener lineListener) { this.dockerClient = dockerClient; this.containerId = containerId; this.lineListener = lineListener; } void setStderrWriter(PrintStream stderrWriter) { this.stderrWriter = stderrWriter; } void setStdoutWriter(PrintStream stdoutWriter) { this.stdoutWriter = stdoutWriter; } public void start() throws IOException, InterruptedException { final String containerShortId = StringUtils.left(containerId, SHORT_ID_LEN); final LogSplitter logSplitter = new LogSplitter(); if (lineListener != null) {
// Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogPrinter.java // public class LogPrinter implements Runnable { // // private static Logger log = LoggerFactory.getLogger(LogPrinter.class); // // private final String prefix; // private final InputStream scannedInputStream; // private final PrintStream output; // private final LineListener lineListener; // // public LogPrinter(String prefix, InputStream scannedInputStream, PrintStream output, LineListener lineListener) { // this.prefix = prefix; // this.scannedInputStream = scannedInputStream; // this.output = output; // this.lineListener = lineListener; // } // // @Override // public void run() { // log.trace("{} printer thread started", prefix); // try (Scanner scanner = new Scanner(scannedInputStream)) { // while (scanner.hasNextLine()) { // String line = scanner.nextLine(); // log.trace("{} line: {}", prefix, line); // if (output != null) { // output.println(prefix + line); // } // if (lineListener != null) { // lineListener.nextLine(line); // } // } // } // log.trace("{} printer thread terminated", prefix); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/logs/LogSplitter.java // public class LogSplitter implements Closeable { // // private final PipedInputStream stdoutInput = new PipedInputStream(); // private final PipedInputStream stderrInput = new PipedInputStream(); // private final PipedInputStream combinedInput = new PipedInputStream(); // // private final PipedOutputStream stdoutPipeOutputStream; // private final PipedOutputStream stderrPipeOutputStream; // private final PipedOutputStream combinedPipeOutputStream; // // private final OutputStream stdoutOutput; // private final OutputStream stderrOutput; // // public LogSplitter() { // try { // this.stdoutPipeOutputStream = new PipedOutputStream(stdoutInput); // this.stderrPipeOutputStream = new PipedOutputStream(stderrInput); // this.combinedPipeOutputStream = new PipedOutputStream(combinedInput); // this.stdoutOutput = new TeeOutputStream(stdoutPipeOutputStream, combinedPipeOutputStream); // this.stderrOutput = new TeeOutputStream(stderrPipeOutputStream, combinedPipeOutputStream); // } catch (IOException e) { // throw new RuntimeException("Unable to create", e); // } // } // // public OutputStream getStdoutOutput() { // return stdoutOutput; // } // // public OutputStream getStderrOutput() { // return stderrOutput; // } // // public InputStream getStdoutInput() { // return stdoutInput; // } // // public InputStream getStderrInput() { // return stderrInput; // } // // public InputStream getCombinedInput() { // return combinedInput; // } // // @Override // public void close() throws IOException { // IOUtils.closeQuietly(stderrInput); // IOUtils.closeQuietly(stdoutInput); // IOUtils.closeQuietly(combinedInput); // IOUtils.closeQuietly(stdoutPipeOutputStream); // IOUtils.closeQuietly(stderrPipeOutputStream); // IOUtils.closeQuietly(combinedPipeOutputStream); // IOUtils.closeQuietly(stdoutOutput); // IOUtils.closeQuietly(stderrOutput); // } // } // // Path: src/main/java/pl/domzal/junit/docker/rule/wait/LineListener.java // public interface LineListener { // void nextLine(String line); // } // Path: src/main/java/pl/domzal/junit/docker/rule/DockerLogs.java import java.io.Closeable; import java.io.IOException; import java.io.PrintStream; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.LogsParam; import com.spotify.docker.client.LogStream; import pl.domzal.junit.docker.rule.logs.LogPrinter; import pl.domzal.junit.docker.rule.logs.LogSplitter; import pl.domzal.junit.docker.rule.wait.LineListener; package pl.domzal.junit.docker.rule; /** * Docker container log binding feature. */ class DockerLogs implements Closeable { private static Logger log = LoggerFactory.getLogger(DockerLogs.class); private static final int NO_OF_THREADS = 4; private static final int SHORT_ID_LEN = 12; private final DockerClient dockerClient; private final String containerId; private final LineListener lineListener; private PrintStream stdoutWriter = System.out; private PrintStream stderrWriter = System.err; private final ThreadFactory threadFactory = new ThreadFactoryBuilder()// .setNameFormat("dockerlog-pool-%d")// .setDaemon(true)// .build(); private final ExecutorService executor = Executors.newFixedThreadPool(NO_OF_THREADS, threadFactory); DockerLogs(DockerClient dockerClient, String containerId, LineListener lineListener) { this.dockerClient = dockerClient; this.containerId = containerId; this.lineListener = lineListener; } void setStderrWriter(PrintStream stderrWriter) { this.stderrWriter = stderrWriter; } void setStdoutWriter(PrintStream stdoutWriter) { this.stdoutWriter = stdoutWriter; } public void start() throws IOException, InterruptedException { final String containerShortId = StringUtils.left(containerId, SHORT_ID_LEN); final LogSplitter logSplitter = new LogSplitter(); if (lineListener != null) {
executor.submit(new LogPrinter("", logSplitter.getCombinedInput(), null, lineListener));
ase34/flyingblocksapi
api/src/main/java/de/ase34/flyingblocksapi/FlyingBlock.java
// Path: api/src/main/java/de/ase34/flyingblocksapi/natives/api/NativeFlyingBlockHandler.java // public abstract class NativeFlyingBlockHandler { // // protected FlyingBlock flyingBlock; // // public NativeFlyingBlockHandler(FlyingBlock flyingBlock) { // this.flyingBlock = flyingBlock; // } // // public abstract void spawnFlyingBlock(Location location); // // public abstract void removeEntites(); // // public abstract void setFlyingBlockLocation(Location location); // // public abstract WitherSkull getBukkitEntity(); // // } // // Path: api/src/main/java/de/ase34/flyingblocksapi/natives/api/NativesAPI.java // public abstract class NativesAPI { // // protected static NativesAPI singleton; // // public static NativesAPI getSingleton() { // return singleton; // } // // public static void setSingleton(NativesAPI singleton) { // NativesAPI.singleton = singleton; // } // // public abstract List<Entity> removeFlyingBlocks(World world); // // public abstract void initialize(); // // public abstract NativeFlyingBlockHandler createFlyingBlockHandler(FlyingBlock flyingBlock); // // }
import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.WitherSkull; import org.bukkit.util.Vector; import de.ase34.flyingblocksapi.natives.api.NativeFlyingBlockHandler; import de.ase34.flyingblocksapi.natives.api.NativesAPI;
/** * flyingblocksapi Copyright (C) 2014 ase34 and contributors * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package de.ase34.flyingblocksapi; /** * Handles the entities required for making a flying block. */ public abstract class FlyingBlock { /** * Default age for the horse. */ public static int AGE = -4077000; /** * Default height offset for the skull. */ public static double OFFSET = 100; /** * Default tracker update interval in ticks. */ public static int UPDATE_INTERVAL = 2; protected final Material material; protected final byte materialData; protected final int trackerUpdateInterval; protected final double heightOffset; protected final int horseAge;
// Path: api/src/main/java/de/ase34/flyingblocksapi/natives/api/NativeFlyingBlockHandler.java // public abstract class NativeFlyingBlockHandler { // // protected FlyingBlock flyingBlock; // // public NativeFlyingBlockHandler(FlyingBlock flyingBlock) { // this.flyingBlock = flyingBlock; // } // // public abstract void spawnFlyingBlock(Location location); // // public abstract void removeEntites(); // // public abstract void setFlyingBlockLocation(Location location); // // public abstract WitherSkull getBukkitEntity(); // // } // // Path: api/src/main/java/de/ase34/flyingblocksapi/natives/api/NativesAPI.java // public abstract class NativesAPI { // // protected static NativesAPI singleton; // // public static NativesAPI getSingleton() { // return singleton; // } // // public static void setSingleton(NativesAPI singleton) { // NativesAPI.singleton = singleton; // } // // public abstract List<Entity> removeFlyingBlocks(World world); // // public abstract void initialize(); // // public abstract NativeFlyingBlockHandler createFlyingBlockHandler(FlyingBlock flyingBlock); // // } // Path: api/src/main/java/de/ase34/flyingblocksapi/FlyingBlock.java import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.WitherSkull; import org.bukkit.util.Vector; import de.ase34.flyingblocksapi.natives.api.NativeFlyingBlockHandler; import de.ase34.flyingblocksapi.natives.api.NativesAPI; /** * flyingblocksapi Copyright (C) 2014 ase34 and contributors * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package de.ase34.flyingblocksapi; /** * Handles the entities required for making a flying block. */ public abstract class FlyingBlock { /** * Default age for the horse. */ public static int AGE = -4077000; /** * Default height offset for the skull. */ public static double OFFSET = 100; /** * Default tracker update interval in ticks. */ public static int UPDATE_INTERVAL = 2; protected final Material material; protected final byte materialData; protected final int trackerUpdateInterval; protected final double heightOffset; protected final int horseAge;
protected NativeFlyingBlockHandler nativeHander;
ase34/flyingblocksapi
api/src/main/java/de/ase34/flyingblocksapi/FlyingBlock.java
// Path: api/src/main/java/de/ase34/flyingblocksapi/natives/api/NativeFlyingBlockHandler.java // public abstract class NativeFlyingBlockHandler { // // protected FlyingBlock flyingBlock; // // public NativeFlyingBlockHandler(FlyingBlock flyingBlock) { // this.flyingBlock = flyingBlock; // } // // public abstract void spawnFlyingBlock(Location location); // // public abstract void removeEntites(); // // public abstract void setFlyingBlockLocation(Location location); // // public abstract WitherSkull getBukkitEntity(); // // } // // Path: api/src/main/java/de/ase34/flyingblocksapi/natives/api/NativesAPI.java // public abstract class NativesAPI { // // protected static NativesAPI singleton; // // public static NativesAPI getSingleton() { // return singleton; // } // // public static void setSingleton(NativesAPI singleton) { // NativesAPI.singleton = singleton; // } // // public abstract List<Entity> removeFlyingBlocks(World world); // // public abstract void initialize(); // // public abstract NativeFlyingBlockHandler createFlyingBlockHandler(FlyingBlock flyingBlock); // // }
import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.WitherSkull; import org.bukkit.util.Vector; import de.ase34.flyingblocksapi.natives.api.NativeFlyingBlockHandler; import de.ase34.flyingblocksapi.natives.api.NativesAPI;
/** * flyingblocksapi Copyright (C) 2014 ase34 and contributors * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package de.ase34.flyingblocksapi; /** * Handles the entities required for making a flying block. */ public abstract class FlyingBlock { /** * Default age for the horse. */ public static int AGE = -4077000; /** * Default height offset for the skull. */ public static double OFFSET = 100; /** * Default tracker update interval in ticks. */ public static int UPDATE_INTERVAL = 2; protected final Material material; protected final byte materialData; protected final int trackerUpdateInterval; protected final double heightOffset; protected final int horseAge; protected NativeFlyingBlockHandler nativeHander; /** * Convenience constructor, uses {@link FlyingBlock#FlyingBlock(Material, byte, int, double, int)} * with {@link FlyingBlock#AGE} as age parameter, {@link FlyingBlock#OFFSET} as offset parameter and * {@link FlyingBlock#UPDATE_INTERVAL} as update interval parameter. * * @param material * The material * @param materialData * The material's data */ public FlyingBlock(Material material, byte materialData) { this(material, materialData, UPDATE_INTERVAL, OFFSET, AGE); } /** * Convenience constructor, uses {@link FlyingBlock#FlyingBlock(Material, byte, int, double, int)} * with {@link FlyingBlock#AGE} as age parameter and {@link FlyingBlock#OFFSET} as offset parameter. * * @param material * The material * @param materialData * The material's data * @param trackerUpdateInterval * The update interval of the tracker (in ticks) */ public FlyingBlock(Material material, byte materialData, int trackerUpdateInterval) { this(material, materialData, trackerUpdateInterval, OFFSET, AGE); } /** * Constructs a new {@link FlyingBlock}. * * @param material * The material * @param materialData * The material's data * @param trackerUpdateInterval * The update interval of the tracker (in ticks) * @param heightOffset * The height offset of the skull * @param horseAge * The age of the horse * * @throws IllegalStateException * Thrown if the singleton of {@link NativesAPI} was not set yet. */ public FlyingBlock(Material material, byte materialData, int trackerUpdateInterval, double heightOffset, int horseAge) { this.material = material; this.materialData = materialData; this.trackerUpdateInterval = trackerUpdateInterval; this.heightOffset = heightOffset; this.horseAge = horseAge;
// Path: api/src/main/java/de/ase34/flyingblocksapi/natives/api/NativeFlyingBlockHandler.java // public abstract class NativeFlyingBlockHandler { // // protected FlyingBlock flyingBlock; // // public NativeFlyingBlockHandler(FlyingBlock flyingBlock) { // this.flyingBlock = flyingBlock; // } // // public abstract void spawnFlyingBlock(Location location); // // public abstract void removeEntites(); // // public abstract void setFlyingBlockLocation(Location location); // // public abstract WitherSkull getBukkitEntity(); // // } // // Path: api/src/main/java/de/ase34/flyingblocksapi/natives/api/NativesAPI.java // public abstract class NativesAPI { // // protected static NativesAPI singleton; // // public static NativesAPI getSingleton() { // return singleton; // } // // public static void setSingleton(NativesAPI singleton) { // NativesAPI.singleton = singleton; // } // // public abstract List<Entity> removeFlyingBlocks(World world); // // public abstract void initialize(); // // public abstract NativeFlyingBlockHandler createFlyingBlockHandler(FlyingBlock flyingBlock); // // } // Path: api/src/main/java/de/ase34/flyingblocksapi/FlyingBlock.java import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.WitherSkull; import org.bukkit.util.Vector; import de.ase34.flyingblocksapi.natives.api.NativeFlyingBlockHandler; import de.ase34.flyingblocksapi.natives.api.NativesAPI; /** * flyingblocksapi Copyright (C) 2014 ase34 and contributors * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package de.ase34.flyingblocksapi; /** * Handles the entities required for making a flying block. */ public abstract class FlyingBlock { /** * Default age for the horse. */ public static int AGE = -4077000; /** * Default height offset for the skull. */ public static double OFFSET = 100; /** * Default tracker update interval in ticks. */ public static int UPDATE_INTERVAL = 2; protected final Material material; protected final byte materialData; protected final int trackerUpdateInterval; protected final double heightOffset; protected final int horseAge; protected NativeFlyingBlockHandler nativeHander; /** * Convenience constructor, uses {@link FlyingBlock#FlyingBlock(Material, byte, int, double, int)} * with {@link FlyingBlock#AGE} as age parameter, {@link FlyingBlock#OFFSET} as offset parameter and * {@link FlyingBlock#UPDATE_INTERVAL} as update interval parameter. * * @param material * The material * @param materialData * The material's data */ public FlyingBlock(Material material, byte materialData) { this(material, materialData, UPDATE_INTERVAL, OFFSET, AGE); } /** * Convenience constructor, uses {@link FlyingBlock#FlyingBlock(Material, byte, int, double, int)} * with {@link FlyingBlock#AGE} as age parameter and {@link FlyingBlock#OFFSET} as offset parameter. * * @param material * The material * @param materialData * The material's data * @param trackerUpdateInterval * The update interval of the tracker (in ticks) */ public FlyingBlock(Material material, byte materialData, int trackerUpdateInterval) { this(material, materialData, trackerUpdateInterval, OFFSET, AGE); } /** * Constructs a new {@link FlyingBlock}. * * @param material * The material * @param materialData * The material's data * @param trackerUpdateInterval * The update interval of the tracker (in ticks) * @param heightOffset * The height offset of the skull * @param horseAge * The age of the horse * * @throws IllegalStateException * Thrown if the singleton of {@link NativesAPI} was not set yet. */ public FlyingBlock(Material material, byte materialData, int trackerUpdateInterval, double heightOffset, int horseAge) { this.material = material; this.materialData = materialData; this.trackerUpdateInterval = trackerUpdateInterval; this.heightOffset = heightOffset; this.horseAge = horseAge;
if (NativesAPI.getSingleton() == null) {