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
baratine/auction
src/main/java/examples/auction/AuctionSettlementImpl.java
// Path: src/main/java/examples/auction/SettlementTransactionState.java // enum AuctionUpdateState // { // SUCCESS, // ROLLED_BACK, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum AuctionWinnerUpdateState // { // SUCCESS, // REJECTED, // ROLLED_BACK, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum PaymentTxState // { // SUCCESS, // PENDING, // FAILED, // REFUNDED, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum UserUpdateState // { // SUCCESS, // REJECTED, // ROLLED_BACK, // NONE // }
import java.util.logging.Logger; import javax.inject.Inject; import io.baratine.service.Ensure; import io.baratine.service.Modify; import io.baratine.service.Result; import io.baratine.service.Service; import io.baratine.service.Services; import io.baratine.vault.Id; import io.baratine.vault.IdAsset; import examples.auction.SettlementTransactionState.AuctionUpdateState; import examples.auction.SettlementTransactionState.AuctionWinnerUpdateState; import examples.auction.SettlementTransactionState.PaymentTxState; import examples.auction.SettlementTransactionState.UserUpdateState;
} public void updateUser(Result<Boolean> status) { if (_state.getUserSettleState() == UserUpdateState.SUCCESS) { status.ok(true); } else { getWinner().addWonAuction(_bid.getAuctionId(), status.then(x -> afterUserUpdated(x))); } } private boolean afterUserUpdated(boolean isAccepted) { if (isAccepted) { _state.setUserSettleState(UserUpdateState.SUCCESS); //audit } else { _state.setUserSettleState(UserUpdateState.REJECTED); //audit } return isAccepted; } public void updateAuction(Result<Boolean> status) { if (_state.getAuctionWinnerUpdateState()
// Path: src/main/java/examples/auction/SettlementTransactionState.java // enum AuctionUpdateState // { // SUCCESS, // ROLLED_BACK, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum AuctionWinnerUpdateState // { // SUCCESS, // REJECTED, // ROLLED_BACK, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum PaymentTxState // { // SUCCESS, // PENDING, // FAILED, // REFUNDED, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum UserUpdateState // { // SUCCESS, // REJECTED, // ROLLED_BACK, // NONE // } // Path: src/main/java/examples/auction/AuctionSettlementImpl.java import java.util.logging.Logger; import javax.inject.Inject; import io.baratine.service.Ensure; import io.baratine.service.Modify; import io.baratine.service.Result; import io.baratine.service.Service; import io.baratine.service.Services; import io.baratine.vault.Id; import io.baratine.vault.IdAsset; import examples.auction.SettlementTransactionState.AuctionUpdateState; import examples.auction.SettlementTransactionState.AuctionWinnerUpdateState; import examples.auction.SettlementTransactionState.PaymentTxState; import examples.auction.SettlementTransactionState.UserUpdateState; } public void updateUser(Result<Boolean> status) { if (_state.getUserSettleState() == UserUpdateState.SUCCESS) { status.ok(true); } else { getWinner().addWonAuction(_bid.getAuctionId(), status.then(x -> afterUserUpdated(x))); } } private boolean afterUserUpdated(boolean isAccepted) { if (isAccepted) { _state.setUserSettleState(UserUpdateState.SUCCESS); //audit } else { _state.setUserSettleState(UserUpdateState.REJECTED); //audit } return isAccepted; } public void updateAuction(Result<Boolean> status) { if (_state.getAuctionWinnerUpdateState()
== AuctionWinnerUpdateState.SUCCESS) {
baratine/auction
src/main/java/examples/auction/AuctionSettlementImpl.java
// Path: src/main/java/examples/auction/SettlementTransactionState.java // enum AuctionUpdateState // { // SUCCESS, // ROLLED_BACK, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum AuctionWinnerUpdateState // { // SUCCESS, // REJECTED, // ROLLED_BACK, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum PaymentTxState // { // SUCCESS, // PENDING, // FAILED, // REFUNDED, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum UserUpdateState // { // SUCCESS, // REJECTED, // ROLLED_BACK, // NONE // }
import java.util.logging.Logger; import javax.inject.Inject; import io.baratine.service.Ensure; import io.baratine.service.Modify; import io.baratine.service.Result; import io.baratine.service.Service; import io.baratine.service.Services; import io.baratine.vault.Id; import io.baratine.vault.IdAsset; import examples.auction.SettlementTransactionState.AuctionUpdateState; import examples.auction.SettlementTransactionState.AuctionWinnerUpdateState; import examples.auction.SettlementTransactionState.PaymentTxState; import examples.auction.SettlementTransactionState.UserUpdateState;
auctionData.set(a); return a != null; })); getWinner().getCreditCard(fork.branch().then(c -> { creditCard.set(c); return c != null; })); fork.join(l -> l.get(0) && l.get(1)); } public void chargeUser(AuctionData auctionData, CreditCard creditCard, Result<Boolean> status) { _paypal.settle(auctionData, _bid, creditCard, getEncodedId(), status.then(x -> processPayment(x))); } private boolean processPayment(Payment payment) { _state.setPayment(payment); boolean result; if (payment.getState().equals(Payment.PaymentState.approved)) {
// Path: src/main/java/examples/auction/SettlementTransactionState.java // enum AuctionUpdateState // { // SUCCESS, // ROLLED_BACK, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum AuctionWinnerUpdateState // { // SUCCESS, // REJECTED, // ROLLED_BACK, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum PaymentTxState // { // SUCCESS, // PENDING, // FAILED, // REFUNDED, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum UserUpdateState // { // SUCCESS, // REJECTED, // ROLLED_BACK, // NONE // } // Path: src/main/java/examples/auction/AuctionSettlementImpl.java import java.util.logging.Logger; import javax.inject.Inject; import io.baratine.service.Ensure; import io.baratine.service.Modify; import io.baratine.service.Result; import io.baratine.service.Service; import io.baratine.service.Services; import io.baratine.vault.Id; import io.baratine.vault.IdAsset; import examples.auction.SettlementTransactionState.AuctionUpdateState; import examples.auction.SettlementTransactionState.AuctionWinnerUpdateState; import examples.auction.SettlementTransactionState.PaymentTxState; import examples.auction.SettlementTransactionState.UserUpdateState; auctionData.set(a); return a != null; })); getWinner().getCreditCard(fork.branch().then(c -> { creditCard.set(c); return c != null; })); fork.join(l -> l.get(0) && l.get(1)); } public void chargeUser(AuctionData auctionData, CreditCard creditCard, Result<Boolean> status) { _paypal.settle(auctionData, _bid, creditCard, getEncodedId(), status.then(x -> processPayment(x))); } private boolean processPayment(Payment payment) { _state.setPayment(payment); boolean result; if (payment.getState().equals(Payment.PaymentState.approved)) {
_state.setPaymentState(PaymentTxState.SUCCESS);
baratine/auction
src/main/java/examples/auction/AuctionSettlementImpl.java
// Path: src/main/java/examples/auction/SettlementTransactionState.java // enum AuctionUpdateState // { // SUCCESS, // ROLLED_BACK, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum AuctionWinnerUpdateState // { // SUCCESS, // REJECTED, // ROLLED_BACK, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum PaymentTxState // { // SUCCESS, // PENDING, // FAILED, // REFUNDED, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum UserUpdateState // { // SUCCESS, // REJECTED, // ROLLED_BACK, // NONE // }
import java.util.logging.Logger; import javax.inject.Inject; import io.baratine.service.Ensure; import io.baratine.service.Modify; import io.baratine.service.Result; import io.baratine.service.Service; import io.baratine.service.Services; import io.baratine.vault.Id; import io.baratine.vault.IdAsset; import examples.auction.SettlementTransactionState.AuctionUpdateState; import examples.auction.SettlementTransactionState.AuctionWinnerUpdateState; import examples.auction.SettlementTransactionState.PaymentTxState; import examples.auction.SettlementTransactionState.UserUpdateState;
boolean result; if (payment.getState().equals(Payment.PaymentState.approved)) { _state.setPaymentState(PaymentTxState.SUCCESS); //audit result = true; } else if (payment.getState().equals(Payment.PaymentState.pending)) { _state.setPaymentState(PaymentTxState.PENDING); //audit result = false; } else { _state.setPaymentState(PaymentTxState.FAILED); //audit result = false; } return result; } private void settleComplete(Result<Status> result) { getAuction().setSettled(result.then((x, r) -> {
// Path: src/main/java/examples/auction/SettlementTransactionState.java // enum AuctionUpdateState // { // SUCCESS, // ROLLED_BACK, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum AuctionWinnerUpdateState // { // SUCCESS, // REJECTED, // ROLLED_BACK, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum PaymentTxState // { // SUCCESS, // PENDING, // FAILED, // REFUNDED, // NONE // } // // Path: src/main/java/examples/auction/SettlementTransactionState.java // enum UserUpdateState // { // SUCCESS, // REJECTED, // ROLLED_BACK, // NONE // } // Path: src/main/java/examples/auction/AuctionSettlementImpl.java import java.util.logging.Logger; import javax.inject.Inject; import io.baratine.service.Ensure; import io.baratine.service.Modify; import io.baratine.service.Result; import io.baratine.service.Service; import io.baratine.service.Services; import io.baratine.vault.Id; import io.baratine.vault.IdAsset; import examples.auction.SettlementTransactionState.AuctionUpdateState; import examples.auction.SettlementTransactionState.AuctionWinnerUpdateState; import examples.auction.SettlementTransactionState.PaymentTxState; import examples.auction.SettlementTransactionState.UserUpdateState; boolean result; if (payment.getState().equals(Payment.PaymentState.approved)) { _state.setPaymentState(PaymentTxState.SUCCESS); //audit result = true; } else if (payment.getState().equals(Payment.PaymentState.pending)) { _state.setPaymentState(PaymentTxState.PENDING); //audit result = false; } else { _state.setPaymentState(PaymentTxState.FAILED); //audit result = false; } return result; } private void settleComplete(Result<Status> result) { getAuction().setSettled(result.then((x, r) -> {
_state.setAuctionStateUpdateState(AuctionUpdateState.SUCCESS);
baratine/auction
src/test/java/examples/auction/AuctionTest.java
// Path: src/main/java/examples/auction/AuctionSession.java // class UserInitData // { // private String user; // private String password; // // private boolean isAdmin; // // public UserInitData() // { // } // // public UserInitData(String user, String password, boolean isAdmin) // { // this.user = user; // this.password = password; // this.isAdmin = isAdmin; // } // // public String getUser() // { // return user; // } // // public String getPassword() // { // return password; // } // // public boolean isAdmin() // { // return isAdmin; // } // // @Override // public String toString() // { // return this.getClass().getSimpleName() + "[" // + user // + ", " // + password // + ']'; // } // }
import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import javax.inject.Inject; import io.baratine.event.Events; import io.baratine.service.Result; import io.baratine.service.Service; import io.baratine.service.Services; import io.baratine.vault.IdAsset; import com.caucho.junit.ConfigurationBaratine; import com.caucho.junit.RunnerBaratine; import com.caucho.junit.ServiceTest; import com.caucho.junit.TestTime; import examples.auction.AuctionSession.UserInitData; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith;
AuctionVaultSync _auctions; @Inject @Service("event:") Events _events; @Inject Services _services; /** * User create correctly sets the user name. */ @Test public void testAuctionCreateName() { UserSync user = createUser("Spock", "Password"); AuctionSync auction = createAuction(user, "book", 15); Assert.assertNotNull(auction); AuctionData data = auction.get(); Assert.assertNotNull(data); Assert.assertEquals(user.get().getEncodedId(), auction.get().getOwnerId()); Assert.assertEquals(data.getTitle(), "book"); } UserSync createUser(String name, String password) { IdAsset id
// Path: src/main/java/examples/auction/AuctionSession.java // class UserInitData // { // private String user; // private String password; // // private boolean isAdmin; // // public UserInitData() // { // } // // public UserInitData(String user, String password, boolean isAdmin) // { // this.user = user; // this.password = password; // this.isAdmin = isAdmin; // } // // public String getUser() // { // return user; // } // // public String getPassword() // { // return password; // } // // public boolean isAdmin() // { // return isAdmin; // } // // @Override // public String toString() // { // return this.getClass().getSimpleName() + "[" // + user // + ", " // + password // + ']'; // } // } // Path: src/test/java/examples/auction/AuctionTest.java import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import javax.inject.Inject; import io.baratine.event.Events; import io.baratine.service.Result; import io.baratine.service.Service; import io.baratine.service.Services; import io.baratine.vault.IdAsset; import com.caucho.junit.ConfigurationBaratine; import com.caucho.junit.RunnerBaratine; import com.caucho.junit.ServiceTest; import com.caucho.junit.TestTime; import examples.auction.AuctionSession.UserInitData; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; AuctionVaultSync _auctions; @Inject @Service("event:") Events _events; @Inject Services _services; /** * User create correctly sets the user name. */ @Test public void testAuctionCreateName() { UserSync user = createUser("Spock", "Password"); AuctionSync auction = createAuction(user, "book", 15); Assert.assertNotNull(auction); AuctionData data = auction.get(); Assert.assertNotNull(data); Assert.assertEquals(user.get().getEncodedId(), auction.get().getOwnerId()); Assert.assertEquals(data.getTitle(), "book"); } UserSync createUser(String name, String password) { IdAsset id
= _users.create(new UserInitData(name, password, false));
ufohust/Gprs_droidplanner
Android/src/com/playuav/android/proxy/mission/item/markers/SurveyMarkerInfoProvider.java
// Path: Android/src/com/playuav/android/proxy/mission/item/MissionItemProxy.java // public class MissionItemProxy { // // /** // * This is the mission item object this class is built around. // */ // private final MissionItem mMissionItem; // // /** // * This is the mission render to which this item belongs. // */ // private final MissionProxy mMission; // // /** // * This is the marker source for this mission item render. // */ // private final List<MarkerInfo> mMarkerInfos; // // public MissionItemProxy(MissionProxy mission, MissionItem missionItem) { // mMission = mission; // mMissionItem = missionItem; // mMarkerInfos = MissionItemMarkerInfo.newInstance(this); // // if(mMissionItem instanceof Survey){ // mMission.getDrone().buildComplexMissionItem((Survey) mMissionItem); // } // else if(mMissionItem instanceof StructureScanner){ // mMission.getDrone().buildComplexMissionItem((StructureScanner) mMissionItem); // } // } // // /** // * Provides access to the owning mission render instance. // * // * @return // */ // public MissionProxy getMissionProxy() { // return mMission; // } // // public MissionProxy getMission(){return mMission;} // // /** // * Provides access to the mission item instance. // * // * @return {@link com.o3dr.services.android.lib.drone.mission.item.MissionItem} object // */ // public MissionItem getMissionItem() { // return mMissionItem; // } // // public MissionDetailFragment getDetailFragment() { // return MissionDetailFragment.newInstance(mMissionItem.getType()); // } // // public List<MarkerInfo> getMarkerInfos() { // return mMarkerInfos; // } // // /** // * @param previousPoint // * Previous point on the path, null if there wasn't a previous // * point // * @return the set of points/coords making up this mission item. // */ // public List<LatLong> getPath(LatLong previousPoint) { // List<LatLong> pathPoints = new ArrayList<LatLong>(); // switch (mMissionItem.getType()) { // case LAND: // case WAYPOINT: // case SPLINE_WAYPOINT: // pathPoints.add(((MissionItem.SpatialItem) mMissionItem).getCoordinate()); // break; // // case CIRCLE: // for (int i = 0; i <= 360; i += 10) { // Circle circle = (Circle) mMissionItem; // double startHeading = 0; // if (previousPoint != null) { // startHeading = MathUtils.getHeadingFromCoordinates(circle.getCoordinate(), // previousPoint); // } // pathPoints.add(MathUtils.newCoordFromBearingAndDistance(circle.getCoordinate(), // startHeading + i, circle.getRadius())); // } // break; // // case SURVEY: // List<LatLong> gridPoints = ((Survey)mMissionItem).getGridPoints(); // if (gridPoints != null && !gridPoints.isEmpty()) { // pathPoints.addAll(gridPoints); // } // break; // // case STRUCTURE_SCANNER: // StructureScanner survey = (StructureScanner)mMissionItem; // pathPoints.addAll(survey.getPath()); // break; // // default: // break; // } // // return pathPoints; // } // }
import com.o3dr.services.android.lib.coordinate.LatLong; import com.o3dr.services.android.lib.drone.mission.item.complex.Survey; import java.util.ArrayList; import java.util.List; import com.playuav.android.maps.MarkerInfo; import com.playuav.android.proxy.mission.item.MissionItemProxy;
package com.playuav.android.proxy.mission.item.markers; /** * */ public class SurveyMarkerInfoProvider { private final Survey mSurvey; private final List<MarkerInfo> mPolygonMarkers = new ArrayList<MarkerInfo>();
// Path: Android/src/com/playuav/android/proxy/mission/item/MissionItemProxy.java // public class MissionItemProxy { // // /** // * This is the mission item object this class is built around. // */ // private final MissionItem mMissionItem; // // /** // * This is the mission render to which this item belongs. // */ // private final MissionProxy mMission; // // /** // * This is the marker source for this mission item render. // */ // private final List<MarkerInfo> mMarkerInfos; // // public MissionItemProxy(MissionProxy mission, MissionItem missionItem) { // mMission = mission; // mMissionItem = missionItem; // mMarkerInfos = MissionItemMarkerInfo.newInstance(this); // // if(mMissionItem instanceof Survey){ // mMission.getDrone().buildComplexMissionItem((Survey) mMissionItem); // } // else if(mMissionItem instanceof StructureScanner){ // mMission.getDrone().buildComplexMissionItem((StructureScanner) mMissionItem); // } // } // // /** // * Provides access to the owning mission render instance. // * // * @return // */ // public MissionProxy getMissionProxy() { // return mMission; // } // // public MissionProxy getMission(){return mMission;} // // /** // * Provides access to the mission item instance. // * // * @return {@link com.o3dr.services.android.lib.drone.mission.item.MissionItem} object // */ // public MissionItem getMissionItem() { // return mMissionItem; // } // // public MissionDetailFragment getDetailFragment() { // return MissionDetailFragment.newInstance(mMissionItem.getType()); // } // // public List<MarkerInfo> getMarkerInfos() { // return mMarkerInfos; // } // // /** // * @param previousPoint // * Previous point on the path, null if there wasn't a previous // * point // * @return the set of points/coords making up this mission item. // */ // public List<LatLong> getPath(LatLong previousPoint) { // List<LatLong> pathPoints = new ArrayList<LatLong>(); // switch (mMissionItem.getType()) { // case LAND: // case WAYPOINT: // case SPLINE_WAYPOINT: // pathPoints.add(((MissionItem.SpatialItem) mMissionItem).getCoordinate()); // break; // // case CIRCLE: // for (int i = 0; i <= 360; i += 10) { // Circle circle = (Circle) mMissionItem; // double startHeading = 0; // if (previousPoint != null) { // startHeading = MathUtils.getHeadingFromCoordinates(circle.getCoordinate(), // previousPoint); // } // pathPoints.add(MathUtils.newCoordFromBearingAndDistance(circle.getCoordinate(), // startHeading + i, circle.getRadius())); // } // break; // // case SURVEY: // List<LatLong> gridPoints = ((Survey)mMissionItem).getGridPoints(); // if (gridPoints != null && !gridPoints.isEmpty()) { // pathPoints.addAll(gridPoints); // } // break; // // case STRUCTURE_SCANNER: // StructureScanner survey = (StructureScanner)mMissionItem; // pathPoints.addAll(survey.getPath()); // break; // // default: // break; // } // // return pathPoints; // } // } // Path: Android/src/com/playuav/android/proxy/mission/item/markers/SurveyMarkerInfoProvider.java import com.o3dr.services.android.lib.coordinate.LatLong; import com.o3dr.services.android.lib.drone.mission.item.complex.Survey; import java.util.ArrayList; import java.util.List; import com.playuav.android.maps.MarkerInfo; import com.playuav.android.proxy.mission.item.MissionItemProxy; package com.playuav.android.proxy.mission.item.markers; /** * */ public class SurveyMarkerInfoProvider { private final Survey mSurvey; private final List<MarkerInfo> mPolygonMarkers = new ArrayList<MarkerInfo>();
protected SurveyMarkerInfoProvider(MissionItemProxy origin) {
ufohust/Gprs_droidplanner
Android/src/com/playuav/android/utils/prefs/DroidPlannerPrefs.java
// Path: Android/src/com/o3dr/services/android/lib/drone/connection/ConnectionType.java // public class ConnectionType { // // /** // * USB connection type // */ // public static final int TYPE_USB = 0; // /** // * Key used to retrieve the usb baud rate from the connection parameter bundle. // */ // public static final String EXTRA_USB_BAUD_RATE = "extra_usb_baud_rate"; // /** // * Default value for the usb baud rate. // */ // public static final int DEFAULT_USB_BAUD_RATE = 57600; // // /** // * UDP connection type // */ // public static final int TYPE_UDP = 1; // /** // * Key used to retrieve the udp server port from the connection parameter bundle // */ // public static final String EXTRA_UDP_SERVER_PORT = "extra_udp_server_port"; // /** // * Default value for the upd server port. // */ // public static final int DEFAULT_UPD_SERVER_PORT = 14550; // // /** // * TCP connection type // */ // public static final int TYPE_TCP = 2; // /** // * Key used to retrieve the tcp server ip from the connection parameter bundle // */ // public static final String EXTRA_TCP_SERVER_IP = "extra_tcp_server_ip"; // /** // * Key used to retrieve the tcp server port from the connection parameter bundle // */ // public static final String EXTRA_TCP_SERVER_PORT = "extra_tcp_server_port"; // // public static final String EXTRA_TCP_SERVER_LOGIN_USER = "xxxx,xxx"; // //public static final String EXTRA_TCP_SERVER_PEER = "xxxxx,xxx"; // /** // * Default value for the tcp server port. // */ // public static final int DEFAULT_TCP_SERVER_PORT = 5763; // /** // * Bluetooth connection type // */ // public static final int TYPE_BLUETOOTH = 3; // /** // * Key used to retrieve the bluetooth address from the connection parameter bundle // */ // public static final String EXTRA_BLUETOOTH_ADDRESS = "extra_bluetooth_address"; // // }
import java.util.UUID; import com.playuav.android.R; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.SparseBooleanArray; import com.o3dr.services.android.lib.drone.connection.ConnectionType; import com.o3dr.services.android.lib.drone.connection.StreamRates;
package com.playuav.android.utils.prefs; /** * Provides structured access to Droidplanner preferences * * Over time it might be good to move the various places that are doing * prefs.getFoo(blah, default) here - to collect prefs in one place and avoid * duplicating string constants (which tend to become stale as code evolves). * This is called the DRY (don't repeat yourself) principle of software * development. * * */ public class DroidPlannerPrefs { /* * Default preference value */ public static final boolean DEFAULT_USAGE_STATISTICS = true;
// Path: Android/src/com/o3dr/services/android/lib/drone/connection/ConnectionType.java // public class ConnectionType { // // /** // * USB connection type // */ // public static final int TYPE_USB = 0; // /** // * Key used to retrieve the usb baud rate from the connection parameter bundle. // */ // public static final String EXTRA_USB_BAUD_RATE = "extra_usb_baud_rate"; // /** // * Default value for the usb baud rate. // */ // public static final int DEFAULT_USB_BAUD_RATE = 57600; // // /** // * UDP connection type // */ // public static final int TYPE_UDP = 1; // /** // * Key used to retrieve the udp server port from the connection parameter bundle // */ // public static final String EXTRA_UDP_SERVER_PORT = "extra_udp_server_port"; // /** // * Default value for the upd server port. // */ // public static final int DEFAULT_UPD_SERVER_PORT = 14550; // // /** // * TCP connection type // */ // public static final int TYPE_TCP = 2; // /** // * Key used to retrieve the tcp server ip from the connection parameter bundle // */ // public static final String EXTRA_TCP_SERVER_IP = "extra_tcp_server_ip"; // /** // * Key used to retrieve the tcp server port from the connection parameter bundle // */ // public static final String EXTRA_TCP_SERVER_PORT = "extra_tcp_server_port"; // // public static final String EXTRA_TCP_SERVER_LOGIN_USER = "xxxx,xxx"; // //public static final String EXTRA_TCP_SERVER_PEER = "xxxxx,xxx"; // /** // * Default value for the tcp server port. // */ // public static final int DEFAULT_TCP_SERVER_PORT = 5763; // /** // * Bluetooth connection type // */ // public static final int TYPE_BLUETOOTH = 3; // /** // * Key used to retrieve the bluetooth address from the connection parameter bundle // */ // public static final String EXTRA_BLUETOOTH_ADDRESS = "extra_bluetooth_address"; // // } // Path: Android/src/com/playuav/android/utils/prefs/DroidPlannerPrefs.java import java.util.UUID; import com.playuav.android.R; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.SparseBooleanArray; import com.o3dr.services.android.lib.drone.connection.ConnectionType; import com.o3dr.services.android.lib.drone.connection.StreamRates; package com.playuav.android.utils.prefs; /** * Provides structured access to Droidplanner preferences * * Over time it might be good to move the various places that are doing * prefs.getFoo(blah, default) here - to collect prefs in one place and avoid * duplicating string constants (which tend to become stale as code evolves). * This is called the DRY (don't repeat yourself) principle of software * development. * * */ public class DroidPlannerPrefs { /* * Default preference value */ public static final boolean DEFAULT_USAGE_STATISTICS = true;
public static final String DEFAULT_CONNECTION_TYPE = String.valueOf(ConnectionType.TYPE_USB);
KursX/Parallator
src/com/kursx/parallator/menu/HelpMenu.java
// Path: src/com/kursx/parallator/Logger.java // public class Logger { // // public static final String DATE_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; // // public static void exception(Exception e) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // e.printStackTrace(pw); // e.printStackTrace(); // File workingDirectory = new File(System.getProperty("user.dir")); // try { // FileChannel fileChannel = new RandomAccessFile( // new File(workingDirectory, ".log"), "rw").getChannel(); // fileChannel.position(fileChannel.size()); // fileChannel.write(ByteBuffer.wrap((getDateTime() + " " + sw.toString() + "\n\n").getBytes())); // fileChannel.close(); // } catch (IOException exc) { // e.printStackTrace(); // } // } // // public static String getDateTime() { // return format(new Date(), DATE_YYYY_MM_DD_HH_MM_SS); // } // // private static String format(final Date date, String template) { // if (date != null && template != null) { // try { // return format(template).format(date); // } catch (final NumberFormatException e) { // Logger.exception(e); // return ""; // } // } // return ""; // } // // public static SimpleDateFormat format(String template) { // return new SimpleDateFormat(template, Locale.getDefault()); // } // } // // Path: src/com/kursx/parallator/Toast.java // public final class Toast { // // public static void makeText(Stage ownerStage, String toastMsg) { // makeText(ownerStage, toastMsg, 2000); // } // // public static void makeText(Stage ownerStage, String toastMsg, int time) { // Platform.runLater(() -> { // Stage toastStage = new Stage(); // toastStage.initOwner(ownerStage); // toastStage.setResizable(false); // toastStage.initStyle(StageStyle.TRANSPARENT); // // Text text = new Text(toastMsg); // text.setFont(Font.font("Verdana", 20)); // text.setFill(Color.WHITE); // // StackPane root = new StackPane(text); // root.setStyle("-fx-background-radius: 20; -fx-background-color: rgba(0, 0, 0, 0.5); -fx-padding: 25px;"); // root.setOpacity(0); // // Scene scene = new Scene(root); // scene.setFill(Color.TRANSPARENT); // toastStage.setScene(scene); // toastStage.show(); // // Timeline fadeInTimeline = new Timeline(); // KeyFrame fadeInKey1 = new KeyFrame(Duration.millis(200), new KeyValue(toastStage.getScene().getRoot().opacityProperty(), 1)); // fadeInTimeline.getKeyFrames().add(fadeInKey1); // fadeInTimeline.setOnFinished((ae) -> new Thread(() -> { // try { // Thread.sleep(time); // } catch (InterruptedException e) { // Logger.exception(e); // } // Timeline fadeOutTimeline = new Timeline(); // KeyFrame fadeOutKey1 = new KeyFrame(Duration.millis(200), new KeyValue(toastStage.getScene().getRoot().opacityProperty(), 0)); // fadeOutTimeline.getKeyFrames().add(fadeOutKey1); // fadeOutTimeline.setOnFinished((aeb) -> toastStage.close()); // fadeOutTimeline.play(); // }).start()); // fadeInTimeline.play(); // }); // } // }
import com.kursx.parallator.Logger; import com.kursx.parallator.Toast; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.stage.Stage; import java.io.File; import java.io.FileOutputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel;
package com.kursx.parallator.menu; public class HelpMenu { public final Menu menu; public HelpMenu(Stage stage) { menu = new Menu("Помощь"); MenuItem about = new MenuItem("О Программе"); MenuItem update = new MenuItem("Обновить программу");
// Path: src/com/kursx/parallator/Logger.java // public class Logger { // // public static final String DATE_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; // // public static void exception(Exception e) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // e.printStackTrace(pw); // e.printStackTrace(); // File workingDirectory = new File(System.getProperty("user.dir")); // try { // FileChannel fileChannel = new RandomAccessFile( // new File(workingDirectory, ".log"), "rw").getChannel(); // fileChannel.position(fileChannel.size()); // fileChannel.write(ByteBuffer.wrap((getDateTime() + " " + sw.toString() + "\n\n").getBytes())); // fileChannel.close(); // } catch (IOException exc) { // e.printStackTrace(); // } // } // // public static String getDateTime() { // return format(new Date(), DATE_YYYY_MM_DD_HH_MM_SS); // } // // private static String format(final Date date, String template) { // if (date != null && template != null) { // try { // return format(template).format(date); // } catch (final NumberFormatException e) { // Logger.exception(e); // return ""; // } // } // return ""; // } // // public static SimpleDateFormat format(String template) { // return new SimpleDateFormat(template, Locale.getDefault()); // } // } // // Path: src/com/kursx/parallator/Toast.java // public final class Toast { // // public static void makeText(Stage ownerStage, String toastMsg) { // makeText(ownerStage, toastMsg, 2000); // } // // public static void makeText(Stage ownerStage, String toastMsg, int time) { // Platform.runLater(() -> { // Stage toastStage = new Stage(); // toastStage.initOwner(ownerStage); // toastStage.setResizable(false); // toastStage.initStyle(StageStyle.TRANSPARENT); // // Text text = new Text(toastMsg); // text.setFont(Font.font("Verdana", 20)); // text.setFill(Color.WHITE); // // StackPane root = new StackPane(text); // root.setStyle("-fx-background-radius: 20; -fx-background-color: rgba(0, 0, 0, 0.5); -fx-padding: 25px;"); // root.setOpacity(0); // // Scene scene = new Scene(root); // scene.setFill(Color.TRANSPARENT); // toastStage.setScene(scene); // toastStage.show(); // // Timeline fadeInTimeline = new Timeline(); // KeyFrame fadeInKey1 = new KeyFrame(Duration.millis(200), new KeyValue(toastStage.getScene().getRoot().opacityProperty(), 1)); // fadeInTimeline.getKeyFrames().add(fadeInKey1); // fadeInTimeline.setOnFinished((ae) -> new Thread(() -> { // try { // Thread.sleep(time); // } catch (InterruptedException e) { // Logger.exception(e); // } // Timeline fadeOutTimeline = new Timeline(); // KeyFrame fadeOutKey1 = new KeyFrame(Duration.millis(200), new KeyValue(toastStage.getScene().getRoot().opacityProperty(), 0)); // fadeOutTimeline.getKeyFrames().add(fadeOutKey1); // fadeOutTimeline.setOnFinished((aeb) -> toastStage.close()); // fadeOutTimeline.play(); // }).start()); // fadeInTimeline.play(); // }); // } // } // Path: src/com/kursx/parallator/menu/HelpMenu.java import com.kursx.parallator.Logger; import com.kursx.parallator.Toast; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.stage.Stage; import java.io.File; import java.io.FileOutputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; package com.kursx.parallator.menu; public class HelpMenu { public final Menu menu; public HelpMenu(Stage stage) { menu = new Menu("Помощь"); MenuItem about = new MenuItem("О Программе"); MenuItem update = new MenuItem("Обновить программу");
about.setOnAction(event -> Toast.makeText(stage, "Parallator v1.2 by KursX \n kursxinc@gmail.com", 5000));
KursX/Parallator
src/com/kursx/parallator/menu/HelpMenu.java
// Path: src/com/kursx/parallator/Logger.java // public class Logger { // // public static final String DATE_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; // // public static void exception(Exception e) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // e.printStackTrace(pw); // e.printStackTrace(); // File workingDirectory = new File(System.getProperty("user.dir")); // try { // FileChannel fileChannel = new RandomAccessFile( // new File(workingDirectory, ".log"), "rw").getChannel(); // fileChannel.position(fileChannel.size()); // fileChannel.write(ByteBuffer.wrap((getDateTime() + " " + sw.toString() + "\n\n").getBytes())); // fileChannel.close(); // } catch (IOException exc) { // e.printStackTrace(); // } // } // // public static String getDateTime() { // return format(new Date(), DATE_YYYY_MM_DD_HH_MM_SS); // } // // private static String format(final Date date, String template) { // if (date != null && template != null) { // try { // return format(template).format(date); // } catch (final NumberFormatException e) { // Logger.exception(e); // return ""; // } // } // return ""; // } // // public static SimpleDateFormat format(String template) { // return new SimpleDateFormat(template, Locale.getDefault()); // } // } // // Path: src/com/kursx/parallator/Toast.java // public final class Toast { // // public static void makeText(Stage ownerStage, String toastMsg) { // makeText(ownerStage, toastMsg, 2000); // } // // public static void makeText(Stage ownerStage, String toastMsg, int time) { // Platform.runLater(() -> { // Stage toastStage = new Stage(); // toastStage.initOwner(ownerStage); // toastStage.setResizable(false); // toastStage.initStyle(StageStyle.TRANSPARENT); // // Text text = new Text(toastMsg); // text.setFont(Font.font("Verdana", 20)); // text.setFill(Color.WHITE); // // StackPane root = new StackPane(text); // root.setStyle("-fx-background-radius: 20; -fx-background-color: rgba(0, 0, 0, 0.5); -fx-padding: 25px;"); // root.setOpacity(0); // // Scene scene = new Scene(root); // scene.setFill(Color.TRANSPARENT); // toastStage.setScene(scene); // toastStage.show(); // // Timeline fadeInTimeline = new Timeline(); // KeyFrame fadeInKey1 = new KeyFrame(Duration.millis(200), new KeyValue(toastStage.getScene().getRoot().opacityProperty(), 1)); // fadeInTimeline.getKeyFrames().add(fadeInKey1); // fadeInTimeline.setOnFinished((ae) -> new Thread(() -> { // try { // Thread.sleep(time); // } catch (InterruptedException e) { // Logger.exception(e); // } // Timeline fadeOutTimeline = new Timeline(); // KeyFrame fadeOutKey1 = new KeyFrame(Duration.millis(200), new KeyValue(toastStage.getScene().getRoot().opacityProperty(), 0)); // fadeOutTimeline.getKeyFrames().add(fadeOutKey1); // fadeOutTimeline.setOnFinished((aeb) -> toastStage.close()); // fadeOutTimeline.play(); // }).start()); // fadeInTimeline.play(); // }); // } // }
import com.kursx.parallator.Logger; import com.kursx.parallator.Toast; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.stage.Stage; import java.io.File; import java.io.FileOutputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel;
package com.kursx.parallator.menu; public class HelpMenu { public final Menu menu; public HelpMenu(Stage stage) { menu = new Menu("Помощь"); MenuItem about = new MenuItem("О Программе"); MenuItem update = new MenuItem("Обновить программу"); about.setOnAction(event -> Toast.makeText(stage, "Parallator v1.2 by KursX \n kursxinc@gmail.com", 5000)); update.setOnAction(event -> update()); menu.getItems().addAll(update, about); } public static void update() { new Thread(() -> { try { File file1 = new File("Parallator.jar"); file1.delete(); URL website = new URL("https://github.com/KursX/Parallator/raw/master/release/Parallator.jar"); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream("Parallator.jar"); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); System.exit(0); } catch (Exception e) {
// Path: src/com/kursx/parallator/Logger.java // public class Logger { // // public static final String DATE_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; // // public static void exception(Exception e) { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // e.printStackTrace(pw); // e.printStackTrace(); // File workingDirectory = new File(System.getProperty("user.dir")); // try { // FileChannel fileChannel = new RandomAccessFile( // new File(workingDirectory, ".log"), "rw").getChannel(); // fileChannel.position(fileChannel.size()); // fileChannel.write(ByteBuffer.wrap((getDateTime() + " " + sw.toString() + "\n\n").getBytes())); // fileChannel.close(); // } catch (IOException exc) { // e.printStackTrace(); // } // } // // public static String getDateTime() { // return format(new Date(), DATE_YYYY_MM_DD_HH_MM_SS); // } // // private static String format(final Date date, String template) { // if (date != null && template != null) { // try { // return format(template).format(date); // } catch (final NumberFormatException e) { // Logger.exception(e); // return ""; // } // } // return ""; // } // // public static SimpleDateFormat format(String template) { // return new SimpleDateFormat(template, Locale.getDefault()); // } // } // // Path: src/com/kursx/parallator/Toast.java // public final class Toast { // // public static void makeText(Stage ownerStage, String toastMsg) { // makeText(ownerStage, toastMsg, 2000); // } // // public static void makeText(Stage ownerStage, String toastMsg, int time) { // Platform.runLater(() -> { // Stage toastStage = new Stage(); // toastStage.initOwner(ownerStage); // toastStage.setResizable(false); // toastStage.initStyle(StageStyle.TRANSPARENT); // // Text text = new Text(toastMsg); // text.setFont(Font.font("Verdana", 20)); // text.setFill(Color.WHITE); // // StackPane root = new StackPane(text); // root.setStyle("-fx-background-radius: 20; -fx-background-color: rgba(0, 0, 0, 0.5); -fx-padding: 25px;"); // root.setOpacity(0); // // Scene scene = new Scene(root); // scene.setFill(Color.TRANSPARENT); // toastStage.setScene(scene); // toastStage.show(); // // Timeline fadeInTimeline = new Timeline(); // KeyFrame fadeInKey1 = new KeyFrame(Duration.millis(200), new KeyValue(toastStage.getScene().getRoot().opacityProperty(), 1)); // fadeInTimeline.getKeyFrames().add(fadeInKey1); // fadeInTimeline.setOnFinished((ae) -> new Thread(() -> { // try { // Thread.sleep(time); // } catch (InterruptedException e) { // Logger.exception(e); // } // Timeline fadeOutTimeline = new Timeline(); // KeyFrame fadeOutKey1 = new KeyFrame(Duration.millis(200), new KeyValue(toastStage.getScene().getRoot().opacityProperty(), 0)); // fadeOutTimeline.getKeyFrames().add(fadeOutKey1); // fadeOutTimeline.setOnFinished((aeb) -> toastStage.close()); // fadeOutTimeline.play(); // }).start()); // fadeInTimeline.play(); // }); // } // } // Path: src/com/kursx/parallator/menu/HelpMenu.java import com.kursx.parallator.Logger; import com.kursx.parallator.Toast; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.stage.Stage; import java.io.File; import java.io.FileOutputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; package com.kursx.parallator.menu; public class HelpMenu { public final Menu menu; public HelpMenu(Stage stage) { menu = new Menu("Помощь"); MenuItem about = new MenuItem("О Программе"); MenuItem update = new MenuItem("Обновить программу"); about.setOnAction(event -> Toast.makeText(stage, "Parallator v1.2 by KursX \n kursxinc@gmail.com", 5000)); update.setOnAction(event -> update()); menu.getItems().addAll(update, about); } public static void update() { new Thread(() -> { try { File file1 = new File("Parallator.jar"); file1.delete(); URL website = new URL("https://github.com/KursX/Parallator/raw/master/release/Parallator.jar"); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream("Parallator.jar"); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); System.exit(0); } catch (Exception e) {
Logger.exception(e);
almondtools/rexlex
src/main/java/com/almondtools/rexlex/pattern/TokenIterator.java
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/automaton/Automaton.java // public interface Automaton { // // String getId(); // TokenType getErrorType(); // // AutomatonProperty getProperty(); // Iterable<String> getSamples(int length); // // <T extends Token> Iterator<T> tokenize(CharProvider chars, TokenFactory<T> factory); // // AutomatonMatcher matcher(); // // Automaton revert(); // // AutomatonExport store(String name); // // } // // Path: src/main/java/com/almondtools/rexlex/automaton/AutomatonMatcher.java // public interface AutomatonMatcher { // // AutomatonMatcher withListener(AutomatonMatcherListener listener); // // AutomatonMatcherListener applyTo(CharProvider chars); // boolean isSuspended(); // AutomatonMatcherListener resume(); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/AutomatonMatcherListener.java // public interface AutomatonMatcherListener { // // /** // * reports a match // * @return true if process should suspend, false if process should resume // */ // boolean reportMatch(CharProvider chars, long start, TokenType accepted); // // /** // * reports a mismatch // * @return true if process should suspend, false if process should resume // */ // boolean recoverMismatch(CharProvider chars, long start); // // }
import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.automaton.Automaton; import com.almondtools.rexlex.automaton.AutomatonMatcher; import com.almondtools.rexlex.automaton.AutomatonMatcherListener; import net.amygdalum.util.io.CharProvider;
package com.almondtools.rexlex.pattern; public class TokenIterator<T extends Token> implements Iterator<T>, AutomatonMatcherListener { private static final TokenType STOP = new TokenType() { @Override public boolean error() { return false; } @Override public boolean accept() { return false; } }; private final Match match;
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/automaton/Automaton.java // public interface Automaton { // // String getId(); // TokenType getErrorType(); // // AutomatonProperty getProperty(); // Iterable<String> getSamples(int length); // // <T extends Token> Iterator<T> tokenize(CharProvider chars, TokenFactory<T> factory); // // AutomatonMatcher matcher(); // // Automaton revert(); // // AutomatonExport store(String name); // // } // // Path: src/main/java/com/almondtools/rexlex/automaton/AutomatonMatcher.java // public interface AutomatonMatcher { // // AutomatonMatcher withListener(AutomatonMatcherListener listener); // // AutomatonMatcherListener applyTo(CharProvider chars); // boolean isSuspended(); // AutomatonMatcherListener resume(); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/AutomatonMatcherListener.java // public interface AutomatonMatcherListener { // // /** // * reports a match // * @return true if process should suspend, false if process should resume // */ // boolean reportMatch(CharProvider chars, long start, TokenType accepted); // // /** // * reports a mismatch // * @return true if process should suspend, false if process should resume // */ // boolean recoverMismatch(CharProvider chars, long start); // // } // Path: src/main/java/com/almondtools/rexlex/pattern/TokenIterator.java import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.automaton.Automaton; import com.almondtools.rexlex.automaton.AutomatonMatcher; import com.almondtools.rexlex.automaton.AutomatonMatcherListener; import net.amygdalum.util.io.CharProvider; package com.almondtools.rexlex.pattern; public class TokenIterator<T extends Token> implements Iterator<T>, AutomatonMatcherListener { private static final TokenType STOP = new TokenType() { @Override public boolean error() { return false; } @Override public boolean accept() { return false; } }; private final Match match;
private AutomatonMatcher matcher;
almondtools/rexlex
src/main/java/com/almondtools/rexlex/pattern/TokenIterator.java
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/automaton/Automaton.java // public interface Automaton { // // String getId(); // TokenType getErrorType(); // // AutomatonProperty getProperty(); // Iterable<String> getSamples(int length); // // <T extends Token> Iterator<T> tokenize(CharProvider chars, TokenFactory<T> factory); // // AutomatonMatcher matcher(); // // Automaton revert(); // // AutomatonExport store(String name); // // } // // Path: src/main/java/com/almondtools/rexlex/automaton/AutomatonMatcher.java // public interface AutomatonMatcher { // // AutomatonMatcher withListener(AutomatonMatcherListener listener); // // AutomatonMatcherListener applyTo(CharProvider chars); // boolean isSuspended(); // AutomatonMatcherListener resume(); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/AutomatonMatcherListener.java // public interface AutomatonMatcherListener { // // /** // * reports a match // * @return true if process should suspend, false if process should resume // */ // boolean reportMatch(CharProvider chars, long start, TokenType accepted); // // /** // * reports a mismatch // * @return true if process should suspend, false if process should resume // */ // boolean recoverMismatch(CharProvider chars, long start); // // }
import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.automaton.Automaton; import com.almondtools.rexlex.automaton.AutomatonMatcher; import com.almondtools.rexlex.automaton.AutomatonMatcherListener; import net.amygdalum.util.io.CharProvider;
package com.almondtools.rexlex.pattern; public class TokenIterator<T extends Token> implements Iterator<T>, AutomatonMatcherListener { private static final TokenType STOP = new TokenType() { @Override public boolean error() { return false; } @Override public boolean accept() { return false; } }; private final Match match; private AutomatonMatcher matcher; private TokenType error; private CharProvider chars;
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/automaton/Automaton.java // public interface Automaton { // // String getId(); // TokenType getErrorType(); // // AutomatonProperty getProperty(); // Iterable<String> getSamples(int length); // // <T extends Token> Iterator<T> tokenize(CharProvider chars, TokenFactory<T> factory); // // AutomatonMatcher matcher(); // // Automaton revert(); // // AutomatonExport store(String name); // // } // // Path: src/main/java/com/almondtools/rexlex/automaton/AutomatonMatcher.java // public interface AutomatonMatcher { // // AutomatonMatcher withListener(AutomatonMatcherListener listener); // // AutomatonMatcherListener applyTo(CharProvider chars); // boolean isSuspended(); // AutomatonMatcherListener resume(); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/AutomatonMatcherListener.java // public interface AutomatonMatcherListener { // // /** // * reports a match // * @return true if process should suspend, false if process should resume // */ // boolean reportMatch(CharProvider chars, long start, TokenType accepted); // // /** // * reports a mismatch // * @return true if process should suspend, false if process should resume // */ // boolean recoverMismatch(CharProvider chars, long start); // // } // Path: src/main/java/com/almondtools/rexlex/pattern/TokenIterator.java import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.automaton.Automaton; import com.almondtools.rexlex.automaton.AutomatonMatcher; import com.almondtools.rexlex.automaton.AutomatonMatcherListener; import net.amygdalum.util.io.CharProvider; package com.almondtools.rexlex.pattern; public class TokenIterator<T extends Token> implements Iterator<T>, AutomatonMatcherListener { private static final TokenType STOP = new TokenType() { @Override public boolean error() { return false; } @Override public boolean accept() { return false; } }; private final Match match; private AutomatonMatcher matcher; private TokenType error; private CharProvider chars;
private TokenFactory<T> factory;
almondtools/rexlex
src/main/java/com/almondtools/rexlex/pattern/TokenIterator.java
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/automaton/Automaton.java // public interface Automaton { // // String getId(); // TokenType getErrorType(); // // AutomatonProperty getProperty(); // Iterable<String> getSamples(int length); // // <T extends Token> Iterator<T> tokenize(CharProvider chars, TokenFactory<T> factory); // // AutomatonMatcher matcher(); // // Automaton revert(); // // AutomatonExport store(String name); // // } // // Path: src/main/java/com/almondtools/rexlex/automaton/AutomatonMatcher.java // public interface AutomatonMatcher { // // AutomatonMatcher withListener(AutomatonMatcherListener listener); // // AutomatonMatcherListener applyTo(CharProvider chars); // boolean isSuspended(); // AutomatonMatcherListener resume(); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/AutomatonMatcherListener.java // public interface AutomatonMatcherListener { // // /** // * reports a match // * @return true if process should suspend, false if process should resume // */ // boolean reportMatch(CharProvider chars, long start, TokenType accepted); // // /** // * reports a mismatch // * @return true if process should suspend, false if process should resume // */ // boolean recoverMismatch(CharProvider chars, long start); // // }
import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.automaton.Automaton; import com.almondtools.rexlex.automaton.AutomatonMatcher; import com.almondtools.rexlex.automaton.AutomatonMatcherListener; import net.amygdalum.util.io.CharProvider;
package com.almondtools.rexlex.pattern; public class TokenIterator<T extends Token> implements Iterator<T>, AutomatonMatcherListener { private static final TokenType STOP = new TokenType() { @Override public boolean error() { return false; } @Override public boolean accept() { return false; } }; private final Match match; private AutomatonMatcher matcher; private TokenType error; private CharProvider chars; private TokenFactory<T> factory; private List<T> buffer;
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/automaton/Automaton.java // public interface Automaton { // // String getId(); // TokenType getErrorType(); // // AutomatonProperty getProperty(); // Iterable<String> getSamples(int length); // // <T extends Token> Iterator<T> tokenize(CharProvider chars, TokenFactory<T> factory); // // AutomatonMatcher matcher(); // // Automaton revert(); // // AutomatonExport store(String name); // // } // // Path: src/main/java/com/almondtools/rexlex/automaton/AutomatonMatcher.java // public interface AutomatonMatcher { // // AutomatonMatcher withListener(AutomatonMatcherListener listener); // // AutomatonMatcherListener applyTo(CharProvider chars); // boolean isSuspended(); // AutomatonMatcherListener resume(); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/AutomatonMatcherListener.java // public interface AutomatonMatcherListener { // // /** // * reports a match // * @return true if process should suspend, false if process should resume // */ // boolean reportMatch(CharProvider chars, long start, TokenType accepted); // // /** // * reports a mismatch // * @return true if process should suspend, false if process should resume // */ // boolean recoverMismatch(CharProvider chars, long start); // // } // Path: src/main/java/com/almondtools/rexlex/pattern/TokenIterator.java import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.automaton.Automaton; import com.almondtools.rexlex.automaton.AutomatonMatcher; import com.almondtools.rexlex.automaton.AutomatonMatcherListener; import net.amygdalum.util.io.CharProvider; package com.almondtools.rexlex.pattern; public class TokenIterator<T extends Token> implements Iterator<T>, AutomatonMatcherListener { private static final TokenType STOP = new TokenType() { @Override public boolean error() { return false; } @Override public boolean accept() { return false; } }; private final Match match; private AutomatonMatcher matcher; private TokenType error; private CharProvider chars; private TokenFactory<T> factory; private List<T> buffer;
public TokenIterator(Automaton automaton, CharProvider chars, TokenFactory<T> factory) {
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/ShortestMatchListener.java
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/pattern/Match.java // public class Match { // // public long start; // public long end; // public String text; // public TokenType type; // // public Match() { // this(-1, -1, null, DefaultTokenType.IGNORE); // } // // private Match(long start, long end, String text, TokenType accepted) { // this.start = start; // this.end = end; // this.text = text; // this.type = accepted; // } // // public static Match create(long start, String text, TokenType type) { // return new Match(start, start + text.length(), text, type); // } // // public static Match create(long start, long end, String text, TokenType type) { // return new Match(start, end, text, type); // } // // public Match consume() { // Match match = create(start, end, text, type); // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // return match; // } // // public Match copy() { // return create(start, end, text, type); // } // // public void reset() { // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // } // // public void init(long start, long end, String text, TokenType type) { // this.start = start; // this.end = end; // this.text = text; // this.type = type; // } // // public void init(long start, String text, TokenType type) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = type; // } // // public void init(long start, String text) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = DefaultTokenType.IGNORE; // } // // public void moveFrom(Match match) { // this.start = match.start; // this.end = match.end; // this.text = match.text; // this.type = match.type; // match.reset(); // } // // public boolean isMatch() { // return text != null; // } // // @Override // public String toString() { // return String.valueOf(start) + ":" + text; // } // // @Override // public int hashCode() { // return 31 + (int) start * 7 + text.hashCode() * 3 + (type != null ? type.hashCode() : 0); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // Match that = (Match) obj; // return this.start == that.start // && this.text.equals(that.text) // && Objects.equals(this.type, that.type); // } // // }
import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.pattern.Match; import net.amygdalum.util.io.CharProvider;
package com.almondtools.rexlex.automaton; public class ShortestMatchListener implements MatchListener { private final Match match; public ShortestMatchListener() { this.match = new Match(); } @Override
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/pattern/Match.java // public class Match { // // public long start; // public long end; // public String text; // public TokenType type; // // public Match() { // this(-1, -1, null, DefaultTokenType.IGNORE); // } // // private Match(long start, long end, String text, TokenType accepted) { // this.start = start; // this.end = end; // this.text = text; // this.type = accepted; // } // // public static Match create(long start, String text, TokenType type) { // return new Match(start, start + text.length(), text, type); // } // // public static Match create(long start, long end, String text, TokenType type) { // return new Match(start, end, text, type); // } // // public Match consume() { // Match match = create(start, end, text, type); // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // return match; // } // // public Match copy() { // return create(start, end, text, type); // } // // public void reset() { // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // } // // public void init(long start, long end, String text, TokenType type) { // this.start = start; // this.end = end; // this.text = text; // this.type = type; // } // // public void init(long start, String text, TokenType type) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = type; // } // // public void init(long start, String text) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = DefaultTokenType.IGNORE; // } // // public void moveFrom(Match match) { // this.start = match.start; // this.end = match.end; // this.text = match.text; // this.type = match.type; // match.reset(); // } // // public boolean isMatch() { // return text != null; // } // // @Override // public String toString() { // return String.valueOf(start) + ":" + text; // } // // @Override // public int hashCode() { // return 31 + (int) start * 7 + text.hashCode() * 3 + (type != null ? type.hashCode() : 0); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // Match that = (Match) obj; // return this.start == that.start // && this.text.equals(that.text) // && Objects.equals(this.type, that.type); // } // // } // Path: src/main/java/com/almondtools/rexlex/automaton/ShortestMatchListener.java import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.pattern.Match; import net.amygdalum.util.io.CharProvider; package com.almondtools.rexlex.automaton; public class ShortestMatchListener implements MatchListener { private final Match match; public ShortestMatchListener() { this.match = new Match(); } @Override
public boolean reportMatch(CharProvider chars, long start, TokenType accepted) {
almondtools/rexlex
src/test/java/com/almondtools/rexlex/pattern/AutomatonTest.java
// Path: src/test/java/com/almondtools/rexlex/automaton/Automatons.java // public static Set<String> matchSamples(Automaton a, String... samples) { // MatchCollector collector = new MatchCollector(); // AutomatonMatcher matcher = a.matcher().withListener(collector); // for (String sample : samples) { // matcher.applyTo(chars(sample)); // } // return new LinkedHashSet<String>(collector.getMatchedTexts()); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/Automaton.java // public interface Automaton { // // String getId(); // TokenType getErrorType(); // // AutomatonProperty getProperty(); // Iterable<String> getSamples(int length); // // <T extends Token> Iterator<T> tokenize(CharProvider chars, TokenFactory<T> factory); // // AutomatonMatcher matcher(); // // Automaton revert(); // // AutomatonExport store(String name); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/Accept.java // public enum Accept implements TokenType { // A,B,C,D,E,F,G,H,I,J,K,L,REMAINDER; // // @Override // public boolean error() { // return false; // } // // @Override // public boolean accept() { // return true; // } // }
import static com.almondtools.rexlex.automaton.Automatons.matchSamples; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.junit.Assert.assertThat; import org.junit.Rule; import org.junit.Test; import com.almondtools.rexlex.automaton.Automaton; import com.almondtools.rexlex.tokens.Accept;
package com.almondtools.rexlex.pattern; public class AutomatonTest { private static final RemainderTokenType REMAINDER = new RemainderTokenType(Accept.REMAINDER); @Rule public AutomatonRule compiler = new AutomatonRule(); @Test public void testNullPattern() throws Exception {
// Path: src/test/java/com/almondtools/rexlex/automaton/Automatons.java // public static Set<String> matchSamples(Automaton a, String... samples) { // MatchCollector collector = new MatchCollector(); // AutomatonMatcher matcher = a.matcher().withListener(collector); // for (String sample : samples) { // matcher.applyTo(chars(sample)); // } // return new LinkedHashSet<String>(collector.getMatchedTexts()); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/Automaton.java // public interface Automaton { // // String getId(); // TokenType getErrorType(); // // AutomatonProperty getProperty(); // Iterable<String> getSamples(int length); // // <T extends Token> Iterator<T> tokenize(CharProvider chars, TokenFactory<T> factory); // // AutomatonMatcher matcher(); // // Automaton revert(); // // AutomatonExport store(String name); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/Accept.java // public enum Accept implements TokenType { // A,B,C,D,E,F,G,H,I,J,K,L,REMAINDER; // // @Override // public boolean error() { // return false; // } // // @Override // public boolean accept() { // return true; // } // } // Path: src/test/java/com/almondtools/rexlex/pattern/AutomatonTest.java import static com.almondtools.rexlex.automaton.Automatons.matchSamples; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.junit.Assert.assertThat; import org.junit.Rule; import org.junit.Test; import com.almondtools.rexlex.automaton.Automaton; import com.almondtools.rexlex.tokens.Accept; package com.almondtools.rexlex.pattern; public class AutomatonTest { private static final RemainderTokenType REMAINDER = new RemainderTokenType(Accept.REMAINDER); @Rule public AutomatonRule compiler = new AutomatonRule(); @Test public void testNullPattern() throws Exception {
Automaton pa = compiler.compile((String) null);
almondtools/rexlex
src/test/java/com/almondtools/rexlex/pattern/AutomatonTest.java
// Path: src/test/java/com/almondtools/rexlex/automaton/Automatons.java // public static Set<String> matchSamples(Automaton a, String... samples) { // MatchCollector collector = new MatchCollector(); // AutomatonMatcher matcher = a.matcher().withListener(collector); // for (String sample : samples) { // matcher.applyTo(chars(sample)); // } // return new LinkedHashSet<String>(collector.getMatchedTexts()); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/Automaton.java // public interface Automaton { // // String getId(); // TokenType getErrorType(); // // AutomatonProperty getProperty(); // Iterable<String> getSamples(int length); // // <T extends Token> Iterator<T> tokenize(CharProvider chars, TokenFactory<T> factory); // // AutomatonMatcher matcher(); // // Automaton revert(); // // AutomatonExport store(String name); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/Accept.java // public enum Accept implements TokenType { // A,B,C,D,E,F,G,H,I,J,K,L,REMAINDER; // // @Override // public boolean error() { // return false; // } // // @Override // public boolean accept() { // return true; // } // }
import static com.almondtools.rexlex.automaton.Automatons.matchSamples; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.junit.Assert.assertThat; import org.junit.Rule; import org.junit.Test; import com.almondtools.rexlex.automaton.Automaton; import com.almondtools.rexlex.tokens.Accept;
package com.almondtools.rexlex.pattern; public class AutomatonTest { private static final RemainderTokenType REMAINDER = new RemainderTokenType(Accept.REMAINDER); @Rule public AutomatonRule compiler = new AutomatonRule(); @Test public void testNullPattern() throws Exception { Automaton pa = compiler.compile((String) null);
// Path: src/test/java/com/almondtools/rexlex/automaton/Automatons.java // public static Set<String> matchSamples(Automaton a, String... samples) { // MatchCollector collector = new MatchCollector(); // AutomatonMatcher matcher = a.matcher().withListener(collector); // for (String sample : samples) { // matcher.applyTo(chars(sample)); // } // return new LinkedHashSet<String>(collector.getMatchedTexts()); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/Automaton.java // public interface Automaton { // // String getId(); // TokenType getErrorType(); // // AutomatonProperty getProperty(); // Iterable<String> getSamples(int length); // // <T extends Token> Iterator<T> tokenize(CharProvider chars, TokenFactory<T> factory); // // AutomatonMatcher matcher(); // // Automaton revert(); // // AutomatonExport store(String name); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/Accept.java // public enum Accept implements TokenType { // A,B,C,D,E,F,G,H,I,J,K,L,REMAINDER; // // @Override // public boolean error() { // return false; // } // // @Override // public boolean accept() { // return true; // } // } // Path: src/test/java/com/almondtools/rexlex/pattern/AutomatonTest.java import static com.almondtools.rexlex.automaton.Automatons.matchSamples; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.junit.Assert.assertThat; import org.junit.Rule; import org.junit.Test; import com.almondtools.rexlex.automaton.Automaton; import com.almondtools.rexlex.tokens.Accept; package com.almondtools.rexlex.pattern; public class AutomatonTest { private static final RemainderTokenType REMAINDER = new RemainderTokenType(Accept.REMAINDER); @Rule public AutomatonRule compiler = new AutomatonRule(); @Test public void testNullPattern() throws Exception { Automaton pa = compiler.compile((String) null);
assertThat(matchSamples(pa, ""), empty());
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/LongestMatchListener.java
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/pattern/Match.java // public class Match { // // public long start; // public long end; // public String text; // public TokenType type; // // public Match() { // this(-1, -1, null, DefaultTokenType.IGNORE); // } // // private Match(long start, long end, String text, TokenType accepted) { // this.start = start; // this.end = end; // this.text = text; // this.type = accepted; // } // // public static Match create(long start, String text, TokenType type) { // return new Match(start, start + text.length(), text, type); // } // // public static Match create(long start, long end, String text, TokenType type) { // return new Match(start, end, text, type); // } // // public Match consume() { // Match match = create(start, end, text, type); // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // return match; // } // // public Match copy() { // return create(start, end, text, type); // } // // public void reset() { // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // } // // public void init(long start, long end, String text, TokenType type) { // this.start = start; // this.end = end; // this.text = text; // this.type = type; // } // // public void init(long start, String text, TokenType type) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = type; // } // // public void init(long start, String text) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = DefaultTokenType.IGNORE; // } // // public void moveFrom(Match match) { // this.start = match.start; // this.end = match.end; // this.text = match.text; // this.type = match.type; // match.reset(); // } // // public boolean isMatch() { // return text != null; // } // // @Override // public String toString() { // return String.valueOf(start) + ":" + text; // } // // @Override // public int hashCode() { // return 31 + (int) start * 7 + text.hashCode() * 3 + (type != null ? type.hashCode() : 0); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // Match that = (Match) obj; // return this.start == that.start // && this.text.equals(that.text) // && Objects.equals(this.type, that.type); // } // // }
import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.pattern.Match; import net.amygdalum.util.io.CharProvider;
package com.almondtools.rexlex.automaton; public class LongestMatchListener implements MatchListener { private final Match match; private final Match nextMatch; public LongestMatchListener() { this.match = new Match(); this.nextMatch = new Match(); } @Override
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/pattern/Match.java // public class Match { // // public long start; // public long end; // public String text; // public TokenType type; // // public Match() { // this(-1, -1, null, DefaultTokenType.IGNORE); // } // // private Match(long start, long end, String text, TokenType accepted) { // this.start = start; // this.end = end; // this.text = text; // this.type = accepted; // } // // public static Match create(long start, String text, TokenType type) { // return new Match(start, start + text.length(), text, type); // } // // public static Match create(long start, long end, String text, TokenType type) { // return new Match(start, end, text, type); // } // // public Match consume() { // Match match = create(start, end, text, type); // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // return match; // } // // public Match copy() { // return create(start, end, text, type); // } // // public void reset() { // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // } // // public void init(long start, long end, String text, TokenType type) { // this.start = start; // this.end = end; // this.text = text; // this.type = type; // } // // public void init(long start, String text, TokenType type) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = type; // } // // public void init(long start, String text) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = DefaultTokenType.IGNORE; // } // // public void moveFrom(Match match) { // this.start = match.start; // this.end = match.end; // this.text = match.text; // this.type = match.type; // match.reset(); // } // // public boolean isMatch() { // return text != null; // } // // @Override // public String toString() { // return String.valueOf(start) + ":" + text; // } // // @Override // public int hashCode() { // return 31 + (int) start * 7 + text.hashCode() * 3 + (type != null ? type.hashCode() : 0); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // Match that = (Match) obj; // return this.start == that.start // && this.text.equals(that.text) // && Objects.equals(this.type, that.type); // } // // } // Path: src/main/java/com/almondtools/rexlex/automaton/LongestMatchListener.java import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.pattern.Match; import net.amygdalum.util.io.CharProvider; package com.almondtools.rexlex.automaton; public class LongestMatchListener implements MatchListener { private final Match match; private final Match nextMatch; public LongestMatchListener() { this.match = new Match(); this.nextMatch = new Match(); } @Override
public boolean reportMatch(CharProvider chars, long start, TokenType accepted) {
almondtools/rexlex
src/test/java/com/almondtools/rexlex/pattern/MatchTest.java
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import static com.almondtools.rexlex.pattern.DefaultTokenType.ACCEPT; import static com.almondtools.rexlex.pattern.DefaultTokenType.ERROR; import static com.almondtools.rexlex.pattern.DefaultTokenType.IGNORE; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import org.junit.Test; import com.almondtools.rexlex.TokenType;
package com.almondtools.rexlex.pattern; public class MatchTest { @Test public void testDefaultMatch() throws Exception { Match match = new Match(); match.init(0, "test"); assertThat(match.start, equalTo(0l)); assertThat(match.end, equalTo(4l)); assertThat(match.text, equalTo("test"));
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/test/java/com/almondtools/rexlex/pattern/MatchTest.java import static com.almondtools.rexlex.pattern.DefaultTokenType.ACCEPT; import static com.almondtools.rexlex.pattern.DefaultTokenType.ERROR; import static com.almondtools.rexlex.pattern.DefaultTokenType.IGNORE; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import org.junit.Test; import com.almondtools.rexlex.TokenType; package com.almondtools.rexlex.pattern; public class MatchTest { @Test public void testDefaultMatch() throws Exception { Match match = new Match(); match.init(0, "test"); assertThat(match.start, equalTo(0l)); assertThat(match.end, equalTo(4l)); assertThat(match.text, equalTo("test"));
assertThat(match.type, equalTo((TokenType) IGNORE));
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/BaseListener.java
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import com.almondtools.rexlex.TokenType; import net.amygdalum.util.io.CharProvider;
package com.almondtools.rexlex.automaton; public class BaseListener implements AutomatonMatcherListener { @Override
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/main/java/com/almondtools/rexlex/automaton/BaseListener.java import com.almondtools.rexlex.TokenType; import net.amygdalum.util.io.CharProvider; package com.almondtools.rexlex.automaton; public class BaseListener implements AutomatonMatcherListener { @Override
public boolean reportMatch(CharProvider chars, long start, TokenType accepted) {
almondtools/rexlex
src/main/java/com/almondtools/rexlex/pattern/Match.java
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import java.util.Objects; import com.almondtools.rexlex.TokenType;
package com.almondtools.rexlex.pattern; public class Match { public long start; public long end; public String text;
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/main/java/com/almondtools/rexlex/pattern/Match.java import java.util.Objects; import com.almondtools.rexlex.TokenType; package com.almondtools.rexlex.pattern; public class Match { public long start; public long end; public String text;
public TokenType type;
almondtools/rexlex
src/main/java/com/almondtools/rexlex/lexer/DynamicLexerBuilder.java
// Path: src/main/java/com/almondtools/rexlex/Lexer.java // public interface Lexer<T extends Token> { // // Iterator<T> lex(String input); // // } // // Path: src/main/java/com/almondtools/rexlex/LexerBuilder.java // public interface LexerBuilder<T extends Token> { // // Lexer<T> build(); // void matchRemainder(TokenType type); // void matchPattern(String pattern, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import java.util.LinkedHashMap; import java.util.Map; import com.almondtools.rexlex.Lexer; import com.almondtools.rexlex.LexerBuilder; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType;
package com.almondtools.rexlex.lexer; public class DynamicLexerBuilder<T extends Token> implements LexerBuilder<T> { private TokenFactory<T> factory;
// Path: src/main/java/com/almondtools/rexlex/Lexer.java // public interface Lexer<T extends Token> { // // Iterator<T> lex(String input); // // } // // Path: src/main/java/com/almondtools/rexlex/LexerBuilder.java // public interface LexerBuilder<T extends Token> { // // Lexer<T> build(); // void matchRemainder(TokenType type); // void matchPattern(String pattern, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/main/java/com/almondtools/rexlex/lexer/DynamicLexerBuilder.java import java.util.LinkedHashMap; import java.util.Map; import com.almondtools.rexlex.Lexer; import com.almondtools.rexlex.LexerBuilder; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; package com.almondtools.rexlex.lexer; public class DynamicLexerBuilder<T extends Token> implements LexerBuilder<T> { private TokenFactory<T> factory;
private Map<String, TokenType> patterns;
almondtools/rexlex
src/main/java/com/almondtools/rexlex/lexer/DynamicLexerBuilder.java
// Path: src/main/java/com/almondtools/rexlex/Lexer.java // public interface Lexer<T extends Token> { // // Iterator<T> lex(String input); // // } // // Path: src/main/java/com/almondtools/rexlex/LexerBuilder.java // public interface LexerBuilder<T extends Token> { // // Lexer<T> build(); // void matchRemainder(TokenType type); // void matchPattern(String pattern, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import java.util.LinkedHashMap; import java.util.Map; import com.almondtools.rexlex.Lexer; import com.almondtools.rexlex.LexerBuilder; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType;
package com.almondtools.rexlex.lexer; public class DynamicLexerBuilder<T extends Token> implements LexerBuilder<T> { private TokenFactory<T> factory; private Map<String, TokenType> patterns; private TokenType remainder; public DynamicLexerBuilder(TokenFactory<T> factory) { this.factory = factory; this.patterns = new LinkedHashMap<String, TokenType>(); } @Override
// Path: src/main/java/com/almondtools/rexlex/Lexer.java // public interface Lexer<T extends Token> { // // Iterator<T> lex(String input); // // } // // Path: src/main/java/com/almondtools/rexlex/LexerBuilder.java // public interface LexerBuilder<T extends Token> { // // Lexer<T> build(); // void matchRemainder(TokenType type); // void matchPattern(String pattern, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/main/java/com/almondtools/rexlex/lexer/DynamicLexerBuilder.java import java.util.LinkedHashMap; import java.util.Map; import com.almondtools.rexlex.Lexer; import com.almondtools.rexlex.LexerBuilder; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; package com.almondtools.rexlex.lexer; public class DynamicLexerBuilder<T extends Token> implements LexerBuilder<T> { private TokenFactory<T> factory; private Map<String, TokenType> patterns; private TokenType remainder; public DynamicLexerBuilder(TokenFactory<T> factory) { this.factory = factory; this.patterns = new LinkedHashMap<String, TokenType>(); } @Override
public Lexer<T> build() {
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/FromTabledAutomaton.java
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import com.almondtools.rexlex.TokenType;
package com.almondtools.rexlex.automaton; public class FromTabledAutomaton { public static class ToGenericAutomaton implements ToAutomaton<TabledAutomaton, GenericAutomaton> { @Override public GenericAutomaton transform(TabledAutomaton automaton) { CharClassMapper relevantChars = automaton.getCharClassMapper(); int charClassCount = automaton.getCharClassCount();
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/main/java/com/almondtools/rexlex/automaton/FromTabledAutomaton.java import com.almondtools.rexlex.TokenType; package com.almondtools.rexlex.automaton; public class FromTabledAutomaton { public static class ToGenericAutomaton implements ToAutomaton<TabledAutomaton, GenericAutomaton> { @Override public GenericAutomaton transform(TabledAutomaton automaton) { CharClassMapper relevantChars = automaton.getCharClassMapper(); int charClassCount = automaton.getCharClassCount();
TokenType[] accept = automaton.getAccept();
almondtools/rexlex
src/test/java/com/almondtools/rexlex/pattern/DefaultMatcherBuilderTest.java
// Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton match(char value) { // State s = new State(); // State e = new State(DefaultTokenType.ACCEPT); // // s.addTransition(new ExactTransition(value, e)); // return new GenericAutomaton(s); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton matchUnlimitedLoop(GenericAutomaton a, int start) { // if (start == 0) { // return matchStarLoop(a); // } else { // GenericAutomaton[] as = copyOf(a, new GenericAutomaton[start + 1], start); // as[start] = matchStarLoop(a.clone()); // return matchConcatenation(as); // } // }
import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.match; import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.matchUnlimitedLoop; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test;
package com.almondtools.rexlex.pattern; public class DefaultMatcherBuilderTest { private DefaultMatcherBuilder builder; @Before public void before() {
// Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton match(char value) { // State s = new State(); // State e = new State(DefaultTokenType.ACCEPT); // // s.addTransition(new ExactTransition(value, e)); // return new GenericAutomaton(s); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton matchUnlimitedLoop(GenericAutomaton a, int start) { // if (start == 0) { // return matchStarLoop(a); // } else { // GenericAutomaton[] as = copyOf(a, new GenericAutomaton[start + 1], start); // as[start] = matchStarLoop(a.clone()); // return matchConcatenation(as); // } // } // Path: src/test/java/com/almondtools/rexlex/pattern/DefaultMatcherBuilderTest.java import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.match; import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.matchUnlimitedLoop; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; package com.almondtools.rexlex.pattern; public class DefaultMatcherBuilderTest { private DefaultMatcherBuilder builder; @Before public void before() {
builder = DefaultMatcherBuilder.from(matchUnlimitedLoop(match('a'), 1));
almondtools/rexlex
src/test/java/com/almondtools/rexlex/pattern/DefaultMatcherBuilderTest.java
// Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton match(char value) { // State s = new State(); // State e = new State(DefaultTokenType.ACCEPT); // // s.addTransition(new ExactTransition(value, e)); // return new GenericAutomaton(s); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton matchUnlimitedLoop(GenericAutomaton a, int start) { // if (start == 0) { // return matchStarLoop(a); // } else { // GenericAutomaton[] as = copyOf(a, new GenericAutomaton[start + 1], start); // as[start] = matchStarLoop(a.clone()); // return matchConcatenation(as); // } // }
import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.match; import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.matchUnlimitedLoop; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test;
package com.almondtools.rexlex.pattern; public class DefaultMatcherBuilderTest { private DefaultMatcherBuilder builder; @Before public void before() {
// Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton match(char value) { // State s = new State(); // State e = new State(DefaultTokenType.ACCEPT); // // s.addTransition(new ExactTransition(value, e)); // return new GenericAutomaton(s); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton matchUnlimitedLoop(GenericAutomaton a, int start) { // if (start == 0) { // return matchStarLoop(a); // } else { // GenericAutomaton[] as = copyOf(a, new GenericAutomaton[start + 1], start); // as[start] = matchStarLoop(a.clone()); // return matchConcatenation(as); // } // } // Path: src/test/java/com/almondtools/rexlex/pattern/DefaultMatcherBuilderTest.java import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.match; import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.matchUnlimitedLoop; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; package com.almondtools.rexlex.pattern; public class DefaultMatcherBuilderTest { private DefaultMatcherBuilder builder; @Before public void before() {
builder = DefaultMatcherBuilder.from(matchUnlimitedLoop(match('a'), 1));
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/AutomatonBuilder.java
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/pattern/PatternOption.java // public interface PatternOption { // // }
import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.pattern.PatternOption; import net.amygdalum.regexparser.RegexNode;
package com.almondtools.rexlex.automaton; public interface AutomatonBuilder extends PatternOption { GenericAutomaton buildFrom(RegexNode node);
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/pattern/PatternOption.java // public interface PatternOption { // // } // Path: src/main/java/com/almondtools/rexlex/automaton/AutomatonBuilder.java import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.pattern.PatternOption; import net.amygdalum.regexparser.RegexNode; package com.almondtools.rexlex.automaton; public interface AutomatonBuilder extends PatternOption { GenericAutomaton buildFrom(RegexNode node);
GenericAutomaton buildFrom(RegexNode node, TokenType type);
almondtools/rexlex
src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java
// Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType;
package com.almondtools.rexlex.tokens; public class TestTokenFactory implements TokenFactory<TestToken>{ @Override
// Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; package com.almondtools.rexlex.tokens; public class TestTokenFactory implements TokenFactory<TestToken>{ @Override
public TestToken createToken(String literal, TokenType type) {
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/Automaton.java
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import java.util.Iterator; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; import net.amygdalum.util.io.CharProvider;
package com.almondtools.rexlex.automaton; public interface Automaton { String getId();
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/main/java/com/almondtools/rexlex/automaton/Automaton.java import java.util.Iterator; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; import net.amygdalum.util.io.CharProvider; package com.almondtools.rexlex.automaton; public interface Automaton { String getId();
TokenType getErrorType();
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/Automaton.java
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import java.util.Iterator; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; import net.amygdalum.util.io.CharProvider;
package com.almondtools.rexlex.automaton; public interface Automaton { String getId(); TokenType getErrorType(); AutomatonProperty getProperty(); Iterable<String> getSamples(int length);
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/main/java/com/almondtools/rexlex/automaton/Automaton.java import java.util.Iterator; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; import net.amygdalum.util.io.CharProvider; package com.almondtools.rexlex.automaton; public interface Automaton { String getId(); TokenType getErrorType(); AutomatonProperty getProperty(); Iterable<String> getSamples(int length);
<T extends Token> Iterator<T> tokenize(CharProvider chars, TokenFactory<T> factory);
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/Automaton.java
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import java.util.Iterator; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; import net.amygdalum.util.io.CharProvider;
package com.almondtools.rexlex.automaton; public interface Automaton { String getId(); TokenType getErrorType(); AutomatonProperty getProperty(); Iterable<String> getSamples(int length);
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenFactory.java // public interface TokenFactory<T extends Token> { // // T createToken(String literal, TokenType type); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/main/java/com/almondtools/rexlex/automaton/Automaton.java import java.util.Iterator; import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenFactory; import com.almondtools.rexlex.TokenType; import net.amygdalum.util.io.CharProvider; package com.almondtools.rexlex.automaton; public interface Automaton { String getId(); TokenType getErrorType(); AutomatonProperty getProperty(); Iterable<String> getSamples(int length);
<T extends Token> Iterator<T> tokenize(CharProvider chars, TokenFactory<T> factory);
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/PrefixCollector.java
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/pattern/Match.java // public class Match { // // public long start; // public long end; // public String text; // public TokenType type; // // public Match() { // this(-1, -1, null, DefaultTokenType.IGNORE); // } // // private Match(long start, long end, String text, TokenType accepted) { // this.start = start; // this.end = end; // this.text = text; // this.type = accepted; // } // // public static Match create(long start, String text, TokenType type) { // return new Match(start, start + text.length(), text, type); // } // // public static Match create(long start, long end, String text, TokenType type) { // return new Match(start, end, text, type); // } // // public Match consume() { // Match match = create(start, end, text, type); // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // return match; // } // // public Match copy() { // return create(start, end, text, type); // } // // public void reset() { // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // } // // public void init(long start, long end, String text, TokenType type) { // this.start = start; // this.end = end; // this.text = text; // this.type = type; // } // // public void init(long start, String text, TokenType type) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = type; // } // // public void init(long start, String text) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = DefaultTokenType.IGNORE; // } // // public void moveFrom(Match match) { // this.start = match.start; // this.end = match.end; // this.text = match.text; // this.type = match.type; // match.reset(); // } // // public boolean isMatch() { // return text != null; // } // // @Override // public String toString() { // return String.valueOf(start) + ":" + text; // } // // @Override // public int hashCode() { // return 31 + (int) start * 7 + text.hashCode() * 3 + (type != null ? type.hashCode() : 0); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // Match that = (Match) obj; // return this.start == that.start // && this.text.equals(that.text) // && Objects.equals(this.type, that.type); // } // // }
import java.util.ArrayList; import java.util.List; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.pattern.Match; import net.amygdalum.util.io.CharProvider;
package com.almondtools.rexlex.automaton; public class PrefixCollector implements AutomatonMatcherListener { private List<Match> matches; public PrefixCollector() { this.matches = new ArrayList<Match>(); } @Override
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/pattern/Match.java // public class Match { // // public long start; // public long end; // public String text; // public TokenType type; // // public Match() { // this(-1, -1, null, DefaultTokenType.IGNORE); // } // // private Match(long start, long end, String text, TokenType accepted) { // this.start = start; // this.end = end; // this.text = text; // this.type = accepted; // } // // public static Match create(long start, String text, TokenType type) { // return new Match(start, start + text.length(), text, type); // } // // public static Match create(long start, long end, String text, TokenType type) { // return new Match(start, end, text, type); // } // // public Match consume() { // Match match = create(start, end, text, type); // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // return match; // } // // public Match copy() { // return create(start, end, text, type); // } // // public void reset() { // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // } // // public void init(long start, long end, String text, TokenType type) { // this.start = start; // this.end = end; // this.text = text; // this.type = type; // } // // public void init(long start, String text, TokenType type) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = type; // } // // public void init(long start, String text) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = DefaultTokenType.IGNORE; // } // // public void moveFrom(Match match) { // this.start = match.start; // this.end = match.end; // this.text = match.text; // this.type = match.type; // match.reset(); // } // // public boolean isMatch() { // return text != null; // } // // @Override // public String toString() { // return String.valueOf(start) + ":" + text; // } // // @Override // public int hashCode() { // return 31 + (int) start * 7 + text.hashCode() * 3 + (type != null ? type.hashCode() : 0); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // Match that = (Match) obj; // return this.start == that.start // && this.text.equals(that.text) // && Objects.equals(this.type, that.type); // } // // } // Path: src/main/java/com/almondtools/rexlex/automaton/PrefixCollector.java import java.util.ArrayList; import java.util.List; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.pattern.Match; import net.amygdalum.util.io.CharProvider; package com.almondtools.rexlex.automaton; public class PrefixCollector implements AutomatonMatcherListener { private List<Match> matches; public PrefixCollector() { this.matches = new ArrayList<Match>(); } @Override
public boolean reportMatch(CharProvider chars, long start, TokenType accepted) {
almondtools/rexlex
src/test/java/com/almondtools/rexlex/lexer/DynamicLexerBuilderTest.java
// Path: src/main/java/com/almondtools/rexlex/Lexer.java // public interface Lexer<T extends Token> { // // Iterator<T> lex(String input); // // } // // Path: src/main/java/com/almondtools/rexlex/LexerBuilder.java // public interface LexerBuilder<T extends Token> { // // Lexer<T> build(); // void matchRemainder(TokenType type); // void matchPattern(String pattern, TokenType type); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/Accept.java // public enum Accept implements TokenType { // A,B,C,D,E,F,G,H,I,J,K,L,REMAINDER; // // @Override // public boolean error() { // return false; // } // // @Override // public boolean accept() { // return true; // } // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import com.almondtools.rexlex.Lexer; import com.almondtools.rexlex.LexerBuilder; import com.almondtools.rexlex.tokens.Accept; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory;
package com.almondtools.rexlex.lexer; public class DynamicLexerBuilderTest { private LexerBuilder<TestToken> lexBuilder; @Before public void before() {
// Path: src/main/java/com/almondtools/rexlex/Lexer.java // public interface Lexer<T extends Token> { // // Iterator<T> lex(String input); // // } // // Path: src/main/java/com/almondtools/rexlex/LexerBuilder.java // public interface LexerBuilder<T extends Token> { // // Lexer<T> build(); // void matchRemainder(TokenType type); // void matchPattern(String pattern, TokenType type); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/Accept.java // public enum Accept implements TokenType { // A,B,C,D,E,F,G,H,I,J,K,L,REMAINDER; // // @Override // public boolean error() { // return false; // } // // @Override // public boolean accept() { // return true; // } // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // } // Path: src/test/java/com/almondtools/rexlex/lexer/DynamicLexerBuilderTest.java import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import com.almondtools.rexlex.Lexer; import com.almondtools.rexlex.LexerBuilder; import com.almondtools.rexlex.tokens.Accept; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; package com.almondtools.rexlex.lexer; public class DynamicLexerBuilderTest { private LexerBuilder<TestToken> lexBuilder; @Before public void before() {
this.lexBuilder = new DynamicLexerBuilder<TestToken>(new TestTokenFactory());
almondtools/rexlex
src/test/java/com/almondtools/rexlex/lexer/DynamicLexerBuilderTest.java
// Path: src/main/java/com/almondtools/rexlex/Lexer.java // public interface Lexer<T extends Token> { // // Iterator<T> lex(String input); // // } // // Path: src/main/java/com/almondtools/rexlex/LexerBuilder.java // public interface LexerBuilder<T extends Token> { // // Lexer<T> build(); // void matchRemainder(TokenType type); // void matchPattern(String pattern, TokenType type); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/Accept.java // public enum Accept implements TokenType { // A,B,C,D,E,F,G,H,I,J,K,L,REMAINDER; // // @Override // public boolean error() { // return false; // } // // @Override // public boolean accept() { // return true; // } // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import com.almondtools.rexlex.Lexer; import com.almondtools.rexlex.LexerBuilder; import com.almondtools.rexlex.tokens.Accept; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory;
package com.almondtools.rexlex.lexer; public class DynamicLexerBuilderTest { private LexerBuilder<TestToken> lexBuilder; @Before public void before() { this.lexBuilder = new DynamicLexerBuilder<TestToken>(new TestTokenFactory()); } @Test public void testAddSingleCharToken() throws Exception {
// Path: src/main/java/com/almondtools/rexlex/Lexer.java // public interface Lexer<T extends Token> { // // Iterator<T> lex(String input); // // } // // Path: src/main/java/com/almondtools/rexlex/LexerBuilder.java // public interface LexerBuilder<T extends Token> { // // Lexer<T> build(); // void matchRemainder(TokenType type); // void matchPattern(String pattern, TokenType type); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/Accept.java // public enum Accept implements TokenType { // A,B,C,D,E,F,G,H,I,J,K,L,REMAINDER; // // @Override // public boolean error() { // return false; // } // // @Override // public boolean accept() { // return true; // } // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // } // Path: src/test/java/com/almondtools/rexlex/lexer/DynamicLexerBuilderTest.java import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import com.almondtools.rexlex.Lexer; import com.almondtools.rexlex.LexerBuilder; import com.almondtools.rexlex.tokens.Accept; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; package com.almondtools.rexlex.lexer; public class DynamicLexerBuilderTest { private LexerBuilder<TestToken> lexBuilder; @Before public void before() { this.lexBuilder = new DynamicLexerBuilder<TestToken>(new TestTokenFactory()); } @Test public void testAddSingleCharToken() throws Exception {
lexBuilder.matchPattern("a", Accept.A);
almondtools/rexlex
src/test/java/com/almondtools/rexlex/lexer/DynamicLexerBuilderTest.java
// Path: src/main/java/com/almondtools/rexlex/Lexer.java // public interface Lexer<T extends Token> { // // Iterator<T> lex(String input); // // } // // Path: src/main/java/com/almondtools/rexlex/LexerBuilder.java // public interface LexerBuilder<T extends Token> { // // Lexer<T> build(); // void matchRemainder(TokenType type); // void matchPattern(String pattern, TokenType type); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/Accept.java // public enum Accept implements TokenType { // A,B,C,D,E,F,G,H,I,J,K,L,REMAINDER; // // @Override // public boolean error() { // return false; // } // // @Override // public boolean accept() { // return true; // } // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import com.almondtools.rexlex.Lexer; import com.almondtools.rexlex.LexerBuilder; import com.almondtools.rexlex.tokens.Accept; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory;
package com.almondtools.rexlex.lexer; public class DynamicLexerBuilderTest { private LexerBuilder<TestToken> lexBuilder; @Before public void before() { this.lexBuilder = new DynamicLexerBuilder<TestToken>(new TestTokenFactory()); } @Test public void testAddSingleCharToken() throws Exception { lexBuilder.matchPattern("a", Accept.A);
// Path: src/main/java/com/almondtools/rexlex/Lexer.java // public interface Lexer<T extends Token> { // // Iterator<T> lex(String input); // // } // // Path: src/main/java/com/almondtools/rexlex/LexerBuilder.java // public interface LexerBuilder<T extends Token> { // // Lexer<T> build(); // void matchRemainder(TokenType type); // void matchPattern(String pattern, TokenType type); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/Accept.java // public enum Accept implements TokenType { // A,B,C,D,E,F,G,H,I,J,K,L,REMAINDER; // // @Override // public boolean error() { // return false; // } // // @Override // public boolean accept() { // return true; // } // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // } // Path: src/test/java/com/almondtools/rexlex/lexer/DynamicLexerBuilderTest.java import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; import com.almondtools.rexlex.Lexer; import com.almondtools.rexlex.LexerBuilder; import com.almondtools.rexlex.tokens.Accept; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; package com.almondtools.rexlex.lexer; public class DynamicLexerBuilderTest { private LexerBuilder<TestToken> lexBuilder; @Before public void before() { this.lexBuilder = new DynamicLexerBuilder<TestToken>(new TestTokenFactory()); } @Test public void testAddSingleCharToken() throws Exception { lexBuilder.matchPattern("a", Accept.A);
Lexer<TestToken> lex = lexBuilder.build();
almondtools/rexlex
src/test/java/com/almondtools/rexlex/pattern/TokenIteratorTest.java
// Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton match(char value) { // State s = new State(); // State e = new State(DefaultTokenType.ACCEPT); // // s.addTransition(new ExactTransition(value, e)); // return new GenericAutomaton(s); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton matchOptional(GenericAutomaton a) { // State s = new State(DefaultTokenType.ACCEPT); // s.addTransition(new EpsilonTransition(a.getStart())); // return new GenericAutomaton(s); // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // }
import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.match; import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.matchOptional; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.NoSuchElementException; import org.junit.Test; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; import net.amygdalum.util.io.StringCharProvider;
package com.almondtools.rexlex.pattern; public class TokenIteratorTest { @Test public void testHasNextOnEmptyChars() throws Exception {
// Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton match(char value) { // State s = new State(); // State e = new State(DefaultTokenType.ACCEPT); // // s.addTransition(new ExactTransition(value, e)); // return new GenericAutomaton(s); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton matchOptional(GenericAutomaton a) { // State s = new State(DefaultTokenType.ACCEPT); // s.addTransition(new EpsilonTransition(a.getStart())); // return new GenericAutomaton(s); // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // } // Path: src/test/java/com/almondtools/rexlex/pattern/TokenIteratorTest.java import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.match; import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.matchOptional; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.NoSuchElementException; import org.junit.Test; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; import net.amygdalum.util.io.StringCharProvider; package com.almondtools.rexlex.pattern; public class TokenIteratorTest { @Test public void testHasNextOnEmptyChars() throws Exception {
TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(match('a'), new StringCharProvider("", 0), new TestTokenFactory());
almondtools/rexlex
src/test/java/com/almondtools/rexlex/pattern/TokenIteratorTest.java
// Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton match(char value) { // State s = new State(); // State e = new State(DefaultTokenType.ACCEPT); // // s.addTransition(new ExactTransition(value, e)); // return new GenericAutomaton(s); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton matchOptional(GenericAutomaton a) { // State s = new State(DefaultTokenType.ACCEPT); // s.addTransition(new EpsilonTransition(a.getStart())); // return new GenericAutomaton(s); // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // }
import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.match; import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.matchOptional; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.NoSuchElementException; import org.junit.Test; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; import net.amygdalum.util.io.StringCharProvider;
package com.almondtools.rexlex.pattern; public class TokenIteratorTest { @Test public void testHasNextOnEmptyChars() throws Exception {
// Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton match(char value) { // State s = new State(); // State e = new State(DefaultTokenType.ACCEPT); // // s.addTransition(new ExactTransition(value, e)); // return new GenericAutomaton(s); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton matchOptional(GenericAutomaton a) { // State s = new State(DefaultTokenType.ACCEPT); // s.addTransition(new EpsilonTransition(a.getStart())); // return new GenericAutomaton(s); // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // } // Path: src/test/java/com/almondtools/rexlex/pattern/TokenIteratorTest.java import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.match; import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.matchOptional; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.NoSuchElementException; import org.junit.Test; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; import net.amygdalum.util.io.StringCharProvider; package com.almondtools.rexlex.pattern; public class TokenIteratorTest { @Test public void testHasNextOnEmptyChars() throws Exception {
TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(match('a'), new StringCharProvider("", 0), new TestTokenFactory());
almondtools/rexlex
src/test/java/com/almondtools/rexlex/pattern/TokenIteratorTest.java
// Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton match(char value) { // State s = new State(); // State e = new State(DefaultTokenType.ACCEPT); // // s.addTransition(new ExactTransition(value, e)); // return new GenericAutomaton(s); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton matchOptional(GenericAutomaton a) { // State s = new State(DefaultTokenType.ACCEPT); // s.addTransition(new EpsilonTransition(a.getStart())); // return new GenericAutomaton(s); // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // }
import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.match; import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.matchOptional; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.NoSuchElementException; import org.junit.Test; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; import net.amygdalum.util.io.StringCharProvider;
package com.almondtools.rexlex.pattern; public class TokenIteratorTest { @Test public void testHasNextOnEmptyChars() throws Exception {
// Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton match(char value) { // State s = new State(); // State e = new State(DefaultTokenType.ACCEPT); // // s.addTransition(new ExactTransition(value, e)); // return new GenericAutomaton(s); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton matchOptional(GenericAutomaton a) { // State s = new State(DefaultTokenType.ACCEPT); // s.addTransition(new EpsilonTransition(a.getStart())); // return new GenericAutomaton(s); // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // } // Path: src/test/java/com/almondtools/rexlex/pattern/TokenIteratorTest.java import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.match; import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.matchOptional; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.NoSuchElementException; import org.junit.Test; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; import net.amygdalum.util.io.StringCharProvider; package com.almondtools.rexlex.pattern; public class TokenIteratorTest { @Test public void testHasNextOnEmptyChars() throws Exception {
TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(match('a'), new StringCharProvider("", 0), new TestTokenFactory());
almondtools/rexlex
src/test/java/com/almondtools/rexlex/pattern/TokenIteratorTest.java
// Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton match(char value) { // State s = new State(); // State e = new State(DefaultTokenType.ACCEPT); // // s.addTransition(new ExactTransition(value, e)); // return new GenericAutomaton(s); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton matchOptional(GenericAutomaton a) { // State s = new State(DefaultTokenType.ACCEPT); // s.addTransition(new EpsilonTransition(a.getStart())); // return new GenericAutomaton(s); // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // }
import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.match; import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.matchOptional; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.NoSuchElementException; import org.junit.Test; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; import net.amygdalum.util.io.StringCharProvider;
package com.almondtools.rexlex.pattern; public class TokenIteratorTest { @Test public void testHasNextOnEmptyChars() throws Exception { TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(match('a'), new StringCharProvider("", 0), new TestTokenFactory()); assertThat(tokenIterator.hasNext(), is(false)); } @Test public void testHasNextRepeatedly() throws Exception { TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(match('a'), new StringCharProvider("a", 0), new TestTokenFactory()); assertThat(tokenIterator.hasNext(), is(true)); assertThat(tokenIterator.hasNext(), is(true)); } @Test public void testHasNextWithFirstMatching() throws Exception { TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(match('a'), new StringCharProvider("aa", 0), new TestTokenFactory()); assertThat(tokenIterator.hasNext(), is(true)); } @Test public void testHasNextWithSecondMatching() throws Exception { TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(match('a'), new StringCharProvider("ba", 0), new TestTokenFactory()); assertThat(tokenIterator.hasNext(), is(true)); } @Test public void testHasNextWithNoneMatching() throws Exception { TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(match('a'), new StringCharProvider("bb", 0), new TestTokenFactory()); assertThat(tokenIterator.hasNext(), is(true)); } @Test public void testHasNextWithEmptyMatch() throws Exception {
// Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton match(char value) { // State s = new State(); // State e = new State(DefaultTokenType.ACCEPT); // // s.addTransition(new ExactTransition(value, e)); // return new GenericAutomaton(s); // } // // Path: src/main/java/com/almondtools/rexlex/automaton/GenericAutomatonBuilder.java // public static GenericAutomaton matchOptional(GenericAutomaton a) { // State s = new State(DefaultTokenType.ACCEPT); // s.addTransition(new EpsilonTransition(a.getStart())); // return new GenericAutomaton(s); // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // } // Path: src/test/java/com/almondtools/rexlex/pattern/TokenIteratorTest.java import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.match; import static com.almondtools.rexlex.automaton.GenericAutomatonBuilder.matchOptional; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.NoSuchElementException; import org.junit.Test; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; import net.amygdalum.util.io.StringCharProvider; package com.almondtools.rexlex.pattern; public class TokenIteratorTest { @Test public void testHasNextOnEmptyChars() throws Exception { TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(match('a'), new StringCharProvider("", 0), new TestTokenFactory()); assertThat(tokenIterator.hasNext(), is(false)); } @Test public void testHasNextRepeatedly() throws Exception { TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(match('a'), new StringCharProvider("a", 0), new TestTokenFactory()); assertThat(tokenIterator.hasNext(), is(true)); assertThat(tokenIterator.hasNext(), is(true)); } @Test public void testHasNextWithFirstMatching() throws Exception { TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(match('a'), new StringCharProvider("aa", 0), new TestTokenFactory()); assertThat(tokenIterator.hasNext(), is(true)); } @Test public void testHasNextWithSecondMatching() throws Exception { TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(match('a'), new StringCharProvider("ba", 0), new TestTokenFactory()); assertThat(tokenIterator.hasNext(), is(true)); } @Test public void testHasNextWithNoneMatching() throws Exception { TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(match('a'), new StringCharProvider("bb", 0), new TestTokenFactory()); assertThat(tokenIterator.hasNext(), is(true)); } @Test public void testHasNextWithEmptyMatch() throws Exception {
TokenIterator<TestToken> tokenIterator = new TokenIterator<TestToken>(matchOptional(match('a')), new StringCharProvider("b", 0), new TestTokenFactory());
almondtools/rexlex
src/test/java/com/almondtools/rexlex/pattern/PatternRule.java
// Path: src/main/java/com/almondtools/rexlex/pattern/PatternOptionUtil.java // public static List<PatternOption> list(PatternOption option, PatternOption... options) { // return Lists.list(option).addAll(options).build(); // }
import static com.almondtools.rexlex.pattern.PatternOptionUtil.list; import org.junit.rules.TestRule;
package com.almondtools.rexlex.pattern; public class PatternRule extends PatternCompilationModeRule implements TestRule { public Pattern compile(String string, PatternOption... options) {
// Path: src/main/java/com/almondtools/rexlex/pattern/PatternOptionUtil.java // public static List<PatternOption> list(PatternOption option, PatternOption... options) { // return Lists.list(option).addAll(options).build(); // } // Path: src/test/java/com/almondtools/rexlex/pattern/PatternRule.java import static com.almondtools.rexlex.pattern.PatternOptionUtil.list; import org.junit.rules.TestRule; package com.almondtools.rexlex.pattern; public class PatternRule extends PatternCompilationModeRule implements TestRule { public Pattern compile(String string, PatternOption... options) {
return Pattern.compile(string, list(mode.getMatcherBuilder(), options));
almondtools/rexlex
src/test/java/com/almondtools/rexlex/pattern/DefaultMatcherBuilderForAutomatonTest.java
// Path: src/main/java/com/almondtools/rexlex/automaton/FromGenericAutomaton.java // public static class ToCompactGenericAutomaton implements ToAutomaton<GenericAutomaton, GenericAutomaton>{ // // @Override // public GenericAutomaton transform(GenericAutomaton automaton) { // return automaton.clone().eliminateEpsilons().eliminateDuplicateFinalStates().eliminateDuplicateTransitions(); // } // // }
import static com.almondtools.rexlex.pattern.DefaultTokenType.ACCEPT; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.almondtools.rexlex.automaton.FromGenericAutomaton.ToCompactGenericAutomaton;
package com.almondtools.rexlex.pattern; public class DefaultMatcherBuilderForAutomatonTest { @Test public void testFind() throws Exception { DefaultMatcherBuilder builder = DefaultMatcherBuilder.from(Pattern.compileGenericAutomaton("c")); Finder matcher = builder.buildFinder("abc"); assertThat(matcher.find(), is(true)); assertThat(matcher.match, notNullValue()); } @Test public void testFindNot() throws Exception { DefaultMatcherBuilder builder = DefaultMatcherBuilder.from(Pattern.compileGenericAutomaton("c")); Finder matcher = builder.buildFinder("ab"); assertThat(matcher.find(), is(false)); assertThat(matcher.match.isMatch(), is(false)); } @Test public void testFindDFA() throws Exception { DefaultMatcherBuilder builder = DefaultMatcherBuilder.from(Pattern.compileGenericAutomaton("(ab|a|bcdef|g)+")); Finder matcher = builder.buildFinder("xxxabcdefg"); List<String> matches = new ArrayList<String>(); while (matcher.find()) { matches.add(matcher.match.text); } assertThat(matches, hasItem("abcdefg")); } @Test public void testFindPosix() throws Exception {
// Path: src/main/java/com/almondtools/rexlex/automaton/FromGenericAutomaton.java // public static class ToCompactGenericAutomaton implements ToAutomaton<GenericAutomaton, GenericAutomaton>{ // // @Override // public GenericAutomaton transform(GenericAutomaton automaton) { // return automaton.clone().eliminateEpsilons().eliminateDuplicateFinalStates().eliminateDuplicateTransitions(); // } // // } // Path: src/test/java/com/almondtools/rexlex/pattern/DefaultMatcherBuilderForAutomatonTest.java import static com.almondtools.rexlex.pattern.DefaultTokenType.ACCEPT; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.almondtools.rexlex.automaton.FromGenericAutomaton.ToCompactGenericAutomaton; package com.almondtools.rexlex.pattern; public class DefaultMatcherBuilderForAutomatonTest { @Test public void testFind() throws Exception { DefaultMatcherBuilder builder = DefaultMatcherBuilder.from(Pattern.compileGenericAutomaton("c")); Finder matcher = builder.buildFinder("abc"); assertThat(matcher.find(), is(true)); assertThat(matcher.match, notNullValue()); } @Test public void testFindNot() throws Exception { DefaultMatcherBuilder builder = DefaultMatcherBuilder.from(Pattern.compileGenericAutomaton("c")); Finder matcher = builder.buildFinder("ab"); assertThat(matcher.find(), is(false)); assertThat(matcher.match.isMatch(), is(false)); } @Test public void testFindDFA() throws Exception { DefaultMatcherBuilder builder = DefaultMatcherBuilder.from(Pattern.compileGenericAutomaton("(ab|a|bcdef|g)+")); Finder matcher = builder.buildFinder("xxxabcdefg"); List<String> matches = new ArrayList<String>(); while (matcher.find()) { matches.add(matcher.match.text); } assertThat(matches, hasItem("abcdefg")); } @Test public void testFindPosix() throws Exception {
DefaultMatcherBuilder builder = (DefaultMatcherBuilder) new DefaultMatcherBuilder(new ToCompactGenericAutomaton()).initWith(Pattern.compileGenericAutomaton("(ab|a|bcdef|g)+"));
almondtools/rexlex
src/main/java/com/almondtools/rexlex/io/MappedCharClassProvider.java
// Path: src/main/java/com/almondtools/rexlex/automaton/CharClassMapper.java // public interface CharClassMapper { // // char[] getRelevantChars(); // // int getIndex(char ch); // // int indexCount(); // // char representative(int i); // // String representatives(List<Integer> path); // // char[] mapped(int decision); // // char lowerBound(int charClass); // // char upperBound(int charClass); // // }
import com.almondtools.rexlex.automaton.CharClassMapper; import net.amygdalum.util.io.CharProvider;
package com.almondtools.rexlex.io; public class MappedCharClassProvider implements CharClassProvider { private CharProvider chars;
// Path: src/main/java/com/almondtools/rexlex/automaton/CharClassMapper.java // public interface CharClassMapper { // // char[] getRelevantChars(); // // int getIndex(char ch); // // int indexCount(); // // char representative(int i); // // String representatives(List<Integer> path); // // char[] mapped(int decision); // // char lowerBound(int charClass); // // char upperBound(int charClass); // // } // Path: src/main/java/com/almondtools/rexlex/io/MappedCharClassProvider.java import com.almondtools.rexlex.automaton.CharClassMapper; import net.amygdalum.util.io.CharProvider; package com.almondtools.rexlex.io; public class MappedCharClassProvider implements CharClassProvider { private CharProvider chars;
private CharClassMapper charClassMapper;
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/TabledAutomatonExport.java
// Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomaton.java // static final int ERROR = 1; // // Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomaton.java // static final int START = 0; // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import static com.almondtools.rexlex.automaton.TabledAutomaton.ERROR; import static com.almondtools.rexlex.automaton.TabledAutomaton.START; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import com.almondtools.rexlex.TokenType; import net.amygdalum.util.text.CharUtils;
package com.almondtools.rexlex.automaton; public class TabledAutomatonExport implements AutomatonExport { private TabledAutomaton automaton; private String name; public TabledAutomatonExport(TabledAutomaton automaton, String name) { this.automaton = automaton; this.name = name; } @Override public void to(OutputStream out) throws IOException { Writer w = null; try { w = new OutputStreamWriter(out, "UTF-8"); w.write("digraph \"" + name + "\" {\n"); writeStart(w); writeAutomaton(w); w.write("}"); } finally { if (w != null) { w.close(); } } } private void writeStart(Writer w) throws IOException { w.write("start [shape=point];\n");
// Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomaton.java // static final int ERROR = 1; // // Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomaton.java // static final int START = 0; // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomatonExport.java import static com.almondtools.rexlex.automaton.TabledAutomaton.ERROR; import static com.almondtools.rexlex.automaton.TabledAutomaton.START; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import com.almondtools.rexlex.TokenType; import net.amygdalum.util.text.CharUtils; package com.almondtools.rexlex.automaton; public class TabledAutomatonExport implements AutomatonExport { private TabledAutomaton automaton; private String name; public TabledAutomatonExport(TabledAutomaton automaton, String name) { this.automaton = automaton; this.name = name; } @Override public void to(OutputStream out) throws IOException { Writer w = null; try { w = new OutputStreamWriter(out, "UTF-8"); w.write("digraph \"" + name + "\" {\n"); writeStart(w); writeAutomaton(w); w.write("}"); } finally { if (w != null) { w.close(); } } } private void writeStart(Writer w) throws IOException { w.write("start [shape=point];\n");
w.write("start -> " + START + ";\n");
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/TabledAutomatonExport.java
// Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomaton.java // static final int ERROR = 1; // // Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomaton.java // static final int START = 0; // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import static com.almondtools.rexlex.automaton.TabledAutomaton.ERROR; import static com.almondtools.rexlex.automaton.TabledAutomaton.START; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import com.almondtools.rexlex.TokenType; import net.amygdalum.util.text.CharUtils;
package com.almondtools.rexlex.automaton; public class TabledAutomatonExport implements AutomatonExport { private TabledAutomaton automaton; private String name; public TabledAutomatonExport(TabledAutomaton automaton, String name) { this.automaton = automaton; this.name = name; } @Override public void to(OutputStream out) throws IOException { Writer w = null; try { w = new OutputStreamWriter(out, "UTF-8"); w.write("digraph \"" + name + "\" {\n"); writeStart(w); writeAutomaton(w); w.write("}"); } finally { if (w != null) { w.close(); } } } private void writeStart(Writer w) throws IOException { w.write("start [shape=point];\n"); w.write("start -> " + START + ";\n"); } public void writeAutomaton(Writer writer) throws IOException { for (int state = 0; state < automaton.getStateCount(); state++) {
// Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomaton.java // static final int ERROR = 1; // // Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomaton.java // static final int START = 0; // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomatonExport.java import static com.almondtools.rexlex.automaton.TabledAutomaton.ERROR; import static com.almondtools.rexlex.automaton.TabledAutomaton.START; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import com.almondtools.rexlex.TokenType; import net.amygdalum.util.text.CharUtils; package com.almondtools.rexlex.automaton; public class TabledAutomatonExport implements AutomatonExport { private TabledAutomaton automaton; private String name; public TabledAutomatonExport(TabledAutomaton automaton, String name) { this.automaton = automaton; this.name = name; } @Override public void to(OutputStream out) throws IOException { Writer w = null; try { w = new OutputStreamWriter(out, "UTF-8"); w.write("digraph \"" + name + "\" {\n"); writeStart(w); writeAutomaton(w); w.write("}"); } finally { if (w != null) { w.close(); } } } private void writeStart(Writer w) throws IOException { w.write("start [shape=point];\n"); w.write("start -> " + START + ";\n"); } public void writeAutomaton(Writer writer) throws IOException { for (int state = 0; state < automaton.getStateCount(); state++) {
if (state == ERROR) {
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/TabledAutomatonExport.java
// Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomaton.java // static final int ERROR = 1; // // Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomaton.java // static final int START = 0; // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import static com.almondtools.rexlex.automaton.TabledAutomaton.ERROR; import static com.almondtools.rexlex.automaton.TabledAutomaton.START; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import com.almondtools.rexlex.TokenType; import net.amygdalum.util.text.CharUtils;
} } } private void writeStart(Writer w) throws IOException { w.write("start [shape=point];\n"); w.write("start -> " + START + ";\n"); } public void writeAutomaton(Writer writer) throws IOException { for (int state = 0; state < automaton.getStateCount(); state++) { if (state == ERROR) { // skip this state continue; } else { writeState(writer, state); } for (int charClass = 0; charClass < automaton.getCharClassCount(); charClass++) { int target = automaton.getTarget(state, charClass); if (target == ERROR) { // skip this transition continue; } else { writeTransition(writer, state, charClass, target); } } } } private void writeState(Writer writer, int state) throws IOException {
// Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomaton.java // static final int ERROR = 1; // // Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomaton.java // static final int START = 0; // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/main/java/com/almondtools/rexlex/automaton/TabledAutomatonExport.java import static com.almondtools.rexlex.automaton.TabledAutomaton.ERROR; import static com.almondtools.rexlex.automaton.TabledAutomaton.START; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import com.almondtools.rexlex.TokenType; import net.amygdalum.util.text.CharUtils; } } } private void writeStart(Writer w) throws IOException { w.write("start [shape=point];\n"); w.write("start -> " + START + ";\n"); } public void writeAutomaton(Writer writer) throws IOException { for (int state = 0; state < automaton.getStateCount(); state++) { if (state == ERROR) { // skip this state continue; } else { writeState(writer, state); } for (int charClass = 0; charClass < automaton.getCharClassCount(); charClass++) { int target = automaton.getTarget(state, charClass); if (target == ERROR) { // skip this transition continue; } else { writeTransition(writer, state, charClass, target); } } } } private void writeState(Writer writer, int state) throws IOException {
TokenType type = automaton.getAccept()[state];
almondtools/rexlex
src/test/java/com/almondtools/rexlex/tokens/TestToken.java
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenType;
package com.almondtools.rexlex.tokens; public class TestToken implements Token { private String literal;
// Path: src/main/java/com/almondtools/rexlex/Token.java // public interface Token { // // String getLiteral(); // TokenType getType(); // // } // // Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java import com.almondtools.rexlex.Token; import com.almondtools.rexlex.TokenType; package com.almondtools.rexlex.tokens; public class TestToken implements Token { private String literal;
private TokenType type;
almondtools/rexlex
src/test/java/com/almondtools/rexlex/lexer/TokenFilterTest.java
// Path: src/main/java/com/almondtools/rexlex/pattern/DefaultTokenType.java // public enum DefaultTokenType implements TokenType { // IGNORE(), // state is acceptable, but match should be ignored // ACCEPT(), // state is acceptable, and match may be returned // ERROR(true) // state is not acceptable and indicates an error // ; // // private boolean error; // // private DefaultTokenType() { // this(false); // } // // private DefaultTokenType(boolean error) { // this.error = error; // } // // @Override // public boolean error() { // return error; // } // // @Override // public boolean accept() { // return !error; // } // // public static DefaultTokenType merge(DefaultTokenType type1, DefaultTokenType type2) { // if (type1 == null) { // return type2; // } else if (type2 == null) { // return type1; // } else if (type1.compareTo(type2) > 0) { // return type1; // } else { // return type2; // } // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // }
import static com.almondtools.rexlex.pattern.DefaultTokenType.IGNORE; import static com.almondtools.rexlex.tokens.Accept.A; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.junit.Test; import com.almondtools.rexlex.pattern.DefaultTokenType; import com.almondtools.rexlex.tokens.TestToken;
package com.almondtools.rexlex.lexer; public class TokenFilterTest { @Test public void testHasNextEmpty() throws Exception {
// Path: src/main/java/com/almondtools/rexlex/pattern/DefaultTokenType.java // public enum DefaultTokenType implements TokenType { // IGNORE(), // state is acceptable, but match should be ignored // ACCEPT(), // state is acceptable, and match may be returned // ERROR(true) // state is not acceptable and indicates an error // ; // // private boolean error; // // private DefaultTokenType() { // this(false); // } // // private DefaultTokenType(boolean error) { // this.error = error; // } // // @Override // public boolean error() { // return error; // } // // @Override // public boolean accept() { // return !error; // } // // public static DefaultTokenType merge(DefaultTokenType type1, DefaultTokenType type2) { // if (type1 == null) { // return type2; // } else if (type2 == null) { // return type1; // } else if (type1.compareTo(type2) > 0) { // return type1; // } else { // return type2; // } // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // Path: src/test/java/com/almondtools/rexlex/lexer/TokenFilterTest.java import static com.almondtools.rexlex.pattern.DefaultTokenType.IGNORE; import static com.almondtools.rexlex.tokens.Accept.A; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.junit.Test; import com.almondtools.rexlex.pattern.DefaultTokenType; import com.almondtools.rexlex.tokens.TestToken; package com.almondtools.rexlex.lexer; public class TokenFilterTest { @Test public void testHasNextEmpty() throws Exception {
Iterator<TestToken> tokens = Collections.<TestToken>emptyList().iterator();
almondtools/rexlex
src/test/java/com/almondtools/rexlex/lexer/TokenFilterTest.java
// Path: src/main/java/com/almondtools/rexlex/pattern/DefaultTokenType.java // public enum DefaultTokenType implements TokenType { // IGNORE(), // state is acceptable, but match should be ignored // ACCEPT(), // state is acceptable, and match may be returned // ERROR(true) // state is not acceptable and indicates an error // ; // // private boolean error; // // private DefaultTokenType() { // this(false); // } // // private DefaultTokenType(boolean error) { // this.error = error; // } // // @Override // public boolean error() { // return error; // } // // @Override // public boolean accept() { // return !error; // } // // public static DefaultTokenType merge(DefaultTokenType type1, DefaultTokenType type2) { // if (type1 == null) { // return type2; // } else if (type2 == null) { // return type1; // } else if (type1.compareTo(type2) > 0) { // return type1; // } else { // return type2; // } // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // }
import static com.almondtools.rexlex.pattern.DefaultTokenType.IGNORE; import static com.almondtools.rexlex.tokens.Accept.A; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.junit.Test; import com.almondtools.rexlex.pattern.DefaultTokenType; import com.almondtools.rexlex.tokens.TestToken;
} @Test(expected=UnsupportedOperationException.class) public void testRemoveOnUnmodifiableIterator() throws Exception { Iterator<TestToken> tokens = Arrays.asList(new TestToken("a", A)).iterator(); TestTokenFilter tokenFilter = new TestTokenFilter(tokens); tokenFilter.next(); tokenFilter.remove(); } @Test public void testRemoveOnModifiableIterator() throws Exception { List<TestToken> tokenList = new ArrayList<TestToken>(); tokenList.add(new TestToken("a", A)); Iterator<TestToken> tokens = tokenList.iterator(); TestTokenFilter tokenFilter = new TestTokenFilter(tokens); assertThat(tokenList, hasSize(1)); tokenFilter.next(); tokenFilter.remove(); assertThat(tokenList, empty()); } private class TestTokenFilter extends TokenFilter<TestToken> { public TestTokenFilter(Iterator<TestToken> tokens) { super(tokens); } @Override public boolean isValid(TestToken token) {
// Path: src/main/java/com/almondtools/rexlex/pattern/DefaultTokenType.java // public enum DefaultTokenType implements TokenType { // IGNORE(), // state is acceptable, but match should be ignored // ACCEPT(), // state is acceptable, and match may be returned // ERROR(true) // state is not acceptable and indicates an error // ; // // private boolean error; // // private DefaultTokenType() { // this(false); // } // // private DefaultTokenType(boolean error) { // this.error = error; // } // // @Override // public boolean error() { // return error; // } // // @Override // public boolean accept() { // return !error; // } // // public static DefaultTokenType merge(DefaultTokenType type1, DefaultTokenType type2) { // if (type1 == null) { // return type2; // } else if (type2 == null) { // return type1; // } else if (type1.compareTo(type2) > 0) { // return type1; // } else { // return type2; // } // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // Path: src/test/java/com/almondtools/rexlex/lexer/TokenFilterTest.java import static com.almondtools.rexlex.pattern.DefaultTokenType.IGNORE; import static com.almondtools.rexlex.tokens.Accept.A; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.junit.Test; import com.almondtools.rexlex.pattern.DefaultTokenType; import com.almondtools.rexlex.tokens.TestToken; } @Test(expected=UnsupportedOperationException.class) public void testRemoveOnUnmodifiableIterator() throws Exception { Iterator<TestToken> tokens = Arrays.asList(new TestToken("a", A)).iterator(); TestTokenFilter tokenFilter = new TestTokenFilter(tokens); tokenFilter.next(); tokenFilter.remove(); } @Test public void testRemoveOnModifiableIterator() throws Exception { List<TestToken> tokenList = new ArrayList<TestToken>(); tokenList.add(new TestToken("a", A)); Iterator<TestToken> tokens = tokenList.iterator(); TestTokenFilter tokenFilter = new TestTokenFilter(tokens); assertThat(tokenList, hasSize(1)); tokenFilter.next(); tokenFilter.remove(); assertThat(tokenList, empty()); } private class TestTokenFilter extends TokenFilter<TestToken> { public TestTokenFilter(Iterator<TestToken> tokens) { super(tokens); } @Override public boolean isValid(TestToken token) {
return token.getType() != DefaultTokenType.IGNORE;
almondtools/rexlex
src/test/java/com/almondtools/rexlex/pattern/DefaultTokenTypeTest.java
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // }
import static com.almondtools.rexlex.pattern.DefaultTokenType.ACCEPT; import static com.almondtools.rexlex.pattern.DefaultTokenType.ERROR; import static com.almondtools.rexlex.pattern.DefaultTokenType.IGNORE; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import java.util.Arrays; import org.junit.Before; import org.junit.Test; import com.almondtools.rexlex.TokenType;
package com.almondtools.rexlex.pattern; public class DefaultTokenTypeTest { private DefaultTokenTypeFactory tokenTypes; @Before public void before() { tokenTypes = new DefaultTokenTypeFactory(); } @Test public void testError() throws Exception { assertThat(ERROR.error(), is(true)); assertThat(IGNORE.error(), is(false)); assertThat(ACCEPT.error(), is(false)); } @Test public void testIgnoreLessThanAcceptAndError() throws Exception {
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // Path: src/test/java/com/almondtools/rexlex/pattern/DefaultTokenTypeTest.java import static com.almondtools.rexlex.pattern.DefaultTokenType.ACCEPT; import static com.almondtools.rexlex.pattern.DefaultTokenType.ERROR; import static com.almondtools.rexlex.pattern.DefaultTokenType.IGNORE; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import java.util.Arrays; import org.junit.Before; import org.junit.Test; import com.almondtools.rexlex.TokenType; package com.almondtools.rexlex.pattern; public class DefaultTokenTypeTest { private DefaultTokenTypeFactory tokenTypes; @Before public void before() { tokenTypes = new DefaultTokenTypeFactory(); } @Test public void testError() throws Exception { assertThat(ERROR.error(), is(true)); assertThat(IGNORE.error(), is(false)); assertThat(ACCEPT.error(), is(false)); } @Test public void testIgnoreLessThanAcceptAndError() throws Exception {
assertThat(tokenTypes.union(IGNORE, ACCEPT), sameInstance((TokenType) ACCEPT));
almondtools/rexlex
src/test/java/com/almondtools/rexlex/lexer/DynamicLexerTest.java
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // }
import static com.almondtools.rexlex.tokens.Accept.A; import static com.almondtools.rexlex.tokens.Accept.B; import static com.almondtools.rexlex.tokens.Accept.REMAINDER; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import java.util.Iterator; import java.util.Map; import org.junit.Before; import org.junit.Test; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; import net.amygdalum.util.builders.Maps;
package com.almondtools.rexlex.lexer; public class DynamicLexerTest { private TestTokenFactory factory; @Before public void before() { this.factory = new TestTokenFactory(); } @Test public void testSimplePatternOnChar() throws Exception {
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // } // Path: src/test/java/com/almondtools/rexlex/lexer/DynamicLexerTest.java import static com.almondtools.rexlex.tokens.Accept.A; import static com.almondtools.rexlex.tokens.Accept.B; import static com.almondtools.rexlex.tokens.Accept.REMAINDER; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import java.util.Iterator; import java.util.Map; import org.junit.Before; import org.junit.Test; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; import net.amygdalum.util.builders.Maps; package com.almondtools.rexlex.lexer; public class DynamicLexerTest { private TestTokenFactory factory; @Before public void before() { this.factory = new TestTokenFactory(); } @Test public void testSimplePatternOnChar() throws Exception {
Map<String, TokenType> patternToTypes = Maps.<String, TokenType>linked()
almondtools/rexlex
src/test/java/com/almondtools/rexlex/lexer/DynamicLexerTest.java
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // }
import static com.almondtools.rexlex.tokens.Accept.A; import static com.almondtools.rexlex.tokens.Accept.B; import static com.almondtools.rexlex.tokens.Accept.REMAINDER; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import java.util.Iterator; import java.util.Map; import org.junit.Before; import org.junit.Test; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; import net.amygdalum.util.builders.Maps;
package com.almondtools.rexlex.lexer; public class DynamicLexerTest { private TestTokenFactory factory; @Before public void before() { this.factory = new TestTokenFactory(); } @Test public void testSimplePatternOnChar() throws Exception { Map<String, TokenType> patternToTypes = Maps.<String, TokenType>linked() .put("a", A) .put("b", B) .build();
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestToken.java // public class TestToken implements Token { // // private String literal; // private TokenType type; // // public TestToken(String literal, TokenType type) { // this.literal = literal; // this.type = type; // } // // @Override // public String getLiteral() { // return literal; // } // // @Override // public TokenType getType() { // return type; // } // // @Override // public int hashCode() { // return literal.hashCode() * 31 + type.hashCode(); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // TestToken other = (TestToken) obj; // return this.type == other.type && this.literal.equals(other.literal); // } // // @Override // public String toString() { // return literal + '(' + type.toString() + ')'; // } // // } // // Path: src/test/java/com/almondtools/rexlex/tokens/TestTokenFactory.java // public class TestTokenFactory implements TokenFactory<TestToken>{ // // @Override // public TestToken createToken(String literal, TokenType type) { // return new TestToken(literal, type); // } // } // Path: src/test/java/com/almondtools/rexlex/lexer/DynamicLexerTest.java import static com.almondtools.rexlex.tokens.Accept.A; import static com.almondtools.rexlex.tokens.Accept.B; import static com.almondtools.rexlex.tokens.Accept.REMAINDER; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import java.util.Iterator; import java.util.Map; import org.junit.Before; import org.junit.Test; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.tokens.TestToken; import com.almondtools.rexlex.tokens.TestTokenFactory; import net.amygdalum.util.builders.Maps; package com.almondtools.rexlex.lexer; public class DynamicLexerTest { private TestTokenFactory factory; @Before public void before() { this.factory = new TestTokenFactory(); } @Test public void testSimplePatternOnChar() throws Exception { Map<String, TokenType> patternToTypes = Maps.<String, TokenType>linked() .put("a", A) .put("b", B) .build();
DynamicLexer<TestToken> lexer = new DynamicLexer<TestToken>(patternToTypes, REMAINDER, factory);
almondtools/rexlex
src/main/java/com/almondtools/rexlex/automaton/MatchCollector.java
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/pattern/Match.java // public class Match { // // public long start; // public long end; // public String text; // public TokenType type; // // public Match() { // this(-1, -1, null, DefaultTokenType.IGNORE); // } // // private Match(long start, long end, String text, TokenType accepted) { // this.start = start; // this.end = end; // this.text = text; // this.type = accepted; // } // // public static Match create(long start, String text, TokenType type) { // return new Match(start, start + text.length(), text, type); // } // // public static Match create(long start, long end, String text, TokenType type) { // return new Match(start, end, text, type); // } // // public Match consume() { // Match match = create(start, end, text, type); // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // return match; // } // // public Match copy() { // return create(start, end, text, type); // } // // public void reset() { // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // } // // public void init(long start, long end, String text, TokenType type) { // this.start = start; // this.end = end; // this.text = text; // this.type = type; // } // // public void init(long start, String text, TokenType type) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = type; // } // // public void init(long start, String text) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = DefaultTokenType.IGNORE; // } // // public void moveFrom(Match match) { // this.start = match.start; // this.end = match.end; // this.text = match.text; // this.type = match.type; // match.reset(); // } // // public boolean isMatch() { // return text != null; // } // // @Override // public String toString() { // return String.valueOf(start) + ":" + text; // } // // @Override // public int hashCode() { // return 31 + (int) start * 7 + text.hashCode() * 3 + (type != null ? type.hashCode() : 0); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // Match that = (Match) obj; // return this.start == that.start // && this.text.equals(that.text) // && Objects.equals(this.type, that.type); // } // // }
import java.util.ArrayList; import java.util.List; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.pattern.Match; import net.amygdalum.util.io.CharProvider;
package com.almondtools.rexlex.automaton; public class MatchCollector implements AutomatonMatcherListener { private List<Match> matches; public MatchCollector() { this.matches = new ArrayList<Match>(); } @Override
// Path: src/main/java/com/almondtools/rexlex/TokenType.java // public interface TokenType { // // boolean error(); // boolean accept(); // // } // // Path: src/main/java/com/almondtools/rexlex/pattern/Match.java // public class Match { // // public long start; // public long end; // public String text; // public TokenType type; // // public Match() { // this(-1, -1, null, DefaultTokenType.IGNORE); // } // // private Match(long start, long end, String text, TokenType accepted) { // this.start = start; // this.end = end; // this.text = text; // this.type = accepted; // } // // public static Match create(long start, String text, TokenType type) { // return new Match(start, start + text.length(), text, type); // } // // public static Match create(long start, long end, String text, TokenType type) { // return new Match(start, end, text, type); // } // // public Match consume() { // Match match = create(start, end, text, type); // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // return match; // } // // public Match copy() { // return create(start, end, text, type); // } // // public void reset() { // this.start = -1; // this.end = -1; // this.text = null; // this.type = DefaultTokenType.IGNORE; // } // // public void init(long start, long end, String text, TokenType type) { // this.start = start; // this.end = end; // this.text = text; // this.type = type; // } // // public void init(long start, String text, TokenType type) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = type; // } // // public void init(long start, String text) { // this.start = start; // this.end = start + text.length(); // this.text = text; // this.type = DefaultTokenType.IGNORE; // } // // public void moveFrom(Match match) { // this.start = match.start; // this.end = match.end; // this.text = match.text; // this.type = match.type; // match.reset(); // } // // public boolean isMatch() { // return text != null; // } // // @Override // public String toString() { // return String.valueOf(start) + ":" + text; // } // // @Override // public int hashCode() { // return 31 + (int) start * 7 + text.hashCode() * 3 + (type != null ? type.hashCode() : 0); // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // Match that = (Match) obj; // return this.start == that.start // && this.text.equals(that.text) // && Objects.equals(this.type, that.type); // } // // } // Path: src/main/java/com/almondtools/rexlex/automaton/MatchCollector.java import java.util.ArrayList; import java.util.List; import com.almondtools.rexlex.TokenType; import com.almondtools.rexlex.pattern.Match; import net.amygdalum.util.io.CharProvider; package com.almondtools.rexlex.automaton; public class MatchCollector implements AutomatonMatcherListener { private List<Match> matches; public MatchCollector() { this.matches = new ArrayList<Match>(); } @Override
public boolean reportMatch(CharProvider chars, long start, TokenType accepted) {
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/services/UserDAOImpl.java
// Path: src/main/java/net/worldline/training/angular/entity/User.java // @Entity // public class User implements Serializable // { // private static final long serialVersionUID = 1L; // @Transient // private int id; // private String uri; // private String firstName; // private String lastName; // private Date lastModified; // private String email; // @Id // private String login; // private String password; // @ElementCollection // @CollectionTable(name="Roles", joinColumns=@JoinColumn(name="user_login")) // @Column(name="roles") // private List<String> roles; // // public User() {} // // public Date getLastModified() { // return lastModified; // } // public void setLastModified(Date lastModified) { // this.lastModified = lastModified; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getUri() { // return uri; // } // public void setUri(String uri) { // this.uri = uri; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getLogin() { // return login; // } // public void setLogin(String login) { // this.login = login; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public List<String> getRoles() { // return roles; // } // public void setRoles(List<String> roles) { // this.roles = roles; // } // }
import net.worldline.training.angular.entity.User; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import java.util.ArrayList; import java.util.Date; import java.util.List;
package net.worldline.training.angular.services; public class UserDAOImpl implements UserDAO { private final Session session; public UserDAOImpl(Session session) { this.session = session; }
// Path: src/main/java/net/worldline/training/angular/entity/User.java // @Entity // public class User implements Serializable // { // private static final long serialVersionUID = 1L; // @Transient // private int id; // private String uri; // private String firstName; // private String lastName; // private Date lastModified; // private String email; // @Id // private String login; // private String password; // @ElementCollection // @CollectionTable(name="Roles", joinColumns=@JoinColumn(name="user_login")) // @Column(name="roles") // private List<String> roles; // // public User() {} // // public Date getLastModified() { // return lastModified; // } // public void setLastModified(Date lastModified) { // this.lastModified = lastModified; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getUri() { // return uri; // } // public void setUri(String uri) { // this.uri = uri; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getLogin() { // return login; // } // public void setLogin(String login) { // this.login = login; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public List<String> getRoles() { // return roles; // } // public void setRoles(List<String> roles) { // this.roles = roles; // } // } // Path: src/main/java/net/worldline/training/angular/services/UserDAOImpl.java import net.worldline.training.angular.entity.User; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import java.util.ArrayList; import java.util.Date; import java.util.List; package net.worldline.training.angular.services; public class UserDAOImpl implements UserDAO { private final Session session; public UserDAOImpl(Session session) { this.session = session; }
public User getUserByLogin(String login){
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/services/NewsDAO.java
// Path: src/main/java/net/worldline/training/angular/entity/News.java // @Entity // public class News { // // private String category; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public News() { // } // // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // }
import java.util.List; import net.worldline.training.angular.entity.News; import org.apache.tapestry5.hibernate.annotations.CommitAfter;
package net.worldline.training.angular.services; public interface NewsDAO {
// Path: src/main/java/net/worldline/training/angular/entity/News.java // @Entity // public class News { // // private String category; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public News() { // } // // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // } // Path: src/main/java/net/worldline/training/angular/services/NewsDAO.java import java.util.List; import net.worldline.training.angular.entity.News; import org.apache.tapestry5.hibernate.annotations.CommitAfter; package net.worldline.training.angular.services; public interface NewsDAO {
List<News> getNews();
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/ws/service/NewsService.java
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/entity/News.java // @Entity // public class News { // // private String category; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public News() { // } // // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // } // // Path: src/main/java/net/worldline/training/angular/services/NewsDAO.java // public interface NewsDAO // { // List<News> getNews(); // // List<News> getNewsByAuthor(String phoneId); // // News getNewsById(int id); // // News getRandomNews(); // // @CommitAfter // void add(News news); // // @CommitAfter // News incLike(int newsId); // // @CommitAfter // News delete(int newsId); // // // // // // }
import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.entity.News; import net.worldline.training.angular.services.NewsDAO; import org.apache.tapestry5.ioc.annotations.Inject; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.util.List;
package net.worldline.training.angular.ws.service; @Path("/app") public class NewsService { @Inject
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/entity/News.java // @Entity // public class News { // // private String category; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public News() { // } // // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // } // // Path: src/main/java/net/worldline/training/angular/services/NewsDAO.java // public interface NewsDAO // { // List<News> getNews(); // // List<News> getNewsByAuthor(String phoneId); // // News getNewsById(int id); // // News getRandomNews(); // // @CommitAfter // void add(News news); // // @CommitAfter // News incLike(int newsId); // // @CommitAfter // News delete(int newsId); // // // // // // } // Path: src/main/java/net/worldline/training/angular/ws/service/NewsService.java import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.entity.News; import net.worldline.training.angular.services.NewsDAO; import org.apache.tapestry5.ioc.annotations.Inject; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.util.List; package net.worldline.training.angular.ws.service; @Path("/app") public class NewsService { @Inject
NewsDAO newsDaoService;
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/ws/service/NewsService.java
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/entity/News.java // @Entity // public class News { // // private String category; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public News() { // } // // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // } // // Path: src/main/java/net/worldline/training/angular/services/NewsDAO.java // public interface NewsDAO // { // List<News> getNews(); // // List<News> getNewsByAuthor(String phoneId); // // News getNewsById(int id); // // News getRandomNews(); // // @CommitAfter // void add(News news); // // @CommitAfter // News incLike(int newsId); // // @CommitAfter // News delete(int newsId); // // // // // // }
import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.entity.News; import net.worldline.training.angular.services.NewsDAO; import org.apache.tapestry5.ioc.annotations.Inject; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.util.List;
package net.worldline.training.angular.ws.service; @Path("/app") public class NewsService { @Inject NewsDAO newsDaoService; @POST @Path("/news") @Consumes("application/json") @PermitAll //@RolesAllowed(RoleConsts.USER_ROLE)
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/entity/News.java // @Entity // public class News { // // private String category; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public News() { // } // // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // } // // Path: src/main/java/net/worldline/training/angular/services/NewsDAO.java // public interface NewsDAO // { // List<News> getNews(); // // List<News> getNewsByAuthor(String phoneId); // // News getNewsById(int id); // // News getRandomNews(); // // @CommitAfter // void add(News news); // // @CommitAfter // News incLike(int newsId); // // @CommitAfter // News delete(int newsId); // // // // // // } // Path: src/main/java/net/worldline/training/angular/ws/service/NewsService.java import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.entity.News; import net.worldline.training.angular.services.NewsDAO; import org.apache.tapestry5.ioc.annotations.Inject; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.util.List; package net.worldline.training.angular.ws.service; @Path("/app") public class NewsService { @Inject NewsDAO newsDaoService; @POST @Path("/news") @Consumes("application/json") @PermitAll //@RolesAllowed(RoleConsts.USER_ROLE)
public Response postNews(News news) {
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/services/NewsDAOImpl.java
// Path: src/main/java/net/worldline/training/angular/entity/News.java // @Entity // public class News { // // private String category; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public News() { // } // // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // }
import net.worldline.training.angular.entity.News; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import java.util.List; import java.util.Random;
package net.worldline.training.angular.services; public class NewsDAOImpl implements NewsDAO { private final Session session; public NewsDAOImpl(Session session) { this.session = session; }
// Path: src/main/java/net/worldline/training/angular/entity/News.java // @Entity // public class News { // // private String category; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public News() { // } // // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // } // Path: src/main/java/net/worldline/training/angular/services/NewsDAOImpl.java import net.worldline.training.angular.entity.News; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import java.util.List; import java.util.Random; package net.worldline.training.angular.services; public class NewsDAOImpl implements NewsDAO { private final Session session; public NewsDAOImpl(Session session) { this.session = session; }
public List<News> getNews() {
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/services/BookCatalogImpl.java
// Path: src/main/java/net/worldline/training/angular/data/bookcat/Book.java // public class Book { // private String id; // private String name; // private String author; // // // // private Float price; // private String description; // private String category; // private boolean isNew; // private BookComment[] comments; // // public Book() { // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Float getPrice() { // return price; // } // // public void setPrice(float price) { // this.price = price; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setIsNew(boolean isNew) { // this.isNew = isNew; // } // // public boolean getIsNew() { // return isNew; // } // // public BookComment[] getComments() { // return comments; // } // // public void setComments(BookComment[] comments) { // this.comments = comments; // } // // // /*public JSONObject getJSONObject() { // String json=""; // ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); // JSONObject ret = new JSONObject(); // // ret.put("id",this.id); // ret.put("author",this.author); // ret.put("name",this.name); // ret.put("description",this.description); // ret.put("category",this.category); // ret.put("price",this.price); // ret.put("isNew",this.isNew); // // try { // // json = ow.writeValueAsString(this.comments); // ret.put("comments",new JSONArray(json)); // // } catch (IOException e) { // e.printStackTrace(); // } // catch (Exception e) { // e.printStackTrace(); // } // // return ret; // // }*/ // }
import java.io.*; import java.util.Hashtable; import java.util.List; import net.worldline.training.angular.data.bookcat.Book; import org.apache.tapestry5.json.JSONArray; import org.apache.tapestry5.json.JSONObject; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectWriter; import org.codehaus.jackson.type.TypeReference;
package net.worldline.training.angular.services; public class BookCatalogImpl implements BookCatalog {
// Path: src/main/java/net/worldline/training/angular/data/bookcat/Book.java // public class Book { // private String id; // private String name; // private String author; // // // // private Float price; // private String description; // private String category; // private boolean isNew; // private BookComment[] comments; // // public Book() { // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Float getPrice() { // return price; // } // // public void setPrice(float price) { // this.price = price; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setIsNew(boolean isNew) { // this.isNew = isNew; // } // // public boolean getIsNew() { // return isNew; // } // // public BookComment[] getComments() { // return comments; // } // // public void setComments(BookComment[] comments) { // this.comments = comments; // } // // // /*public JSONObject getJSONObject() { // String json=""; // ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); // JSONObject ret = new JSONObject(); // // ret.put("id",this.id); // ret.put("author",this.author); // ret.put("name",this.name); // ret.put("description",this.description); // ret.put("category",this.category); // ret.put("price",this.price); // ret.put("isNew",this.isNew); // // try { // // json = ow.writeValueAsString(this.comments); // ret.put("comments",new JSONArray(json)); // // } catch (IOException e) { // e.printStackTrace(); // } // catch (Exception e) { // e.printStackTrace(); // } // // return ret; // // }*/ // } // Path: src/main/java/net/worldline/training/angular/services/BookCatalogImpl.java import java.io.*; import java.util.Hashtable; import java.util.List; import net.worldline.training.angular.data.bookcat.Book; import org.apache.tapestry5.json.JSONArray; import org.apache.tapestry5.json.JSONObject; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectWriter; import org.codehaus.jackson.type.TypeReference; package net.worldline.training.angular.services; public class BookCatalogImpl implements BookCatalog {
private List<Book> catalog;
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/services/BookCatalog.java
// Path: src/main/java/net/worldline/training/angular/data/bookcat/Book.java // public class Book { // private String id; // private String name; // private String author; // // // // private Float price; // private String description; // private String category; // private boolean isNew; // private BookComment[] comments; // // public Book() { // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Float getPrice() { // return price; // } // // public void setPrice(float price) { // this.price = price; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setIsNew(boolean isNew) { // this.isNew = isNew; // } // // public boolean getIsNew() { // return isNew; // } // // public BookComment[] getComments() { // return comments; // } // // public void setComments(BookComment[] comments) { // this.comments = comments; // } // // // /*public JSONObject getJSONObject() { // String json=""; // ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); // JSONObject ret = new JSONObject(); // // ret.put("id",this.id); // ret.put("author",this.author); // ret.put("name",this.name); // ret.put("description",this.description); // ret.put("category",this.category); // ret.put("price",this.price); // ret.put("isNew",this.isNew); // // try { // // json = ow.writeValueAsString(this.comments); // ret.put("comments",new JSONArray(json)); // // } catch (IOException e) { // e.printStackTrace(); // } // catch (Exception e) { // e.printStackTrace(); // } // // return ret; // // }*/ // }
import java.util.List; import net.worldline.training.angular.data.bookcat.Book;
package net.worldline.training.angular.services; public interface BookCatalog { /** * Provides a list of all phone in an indeterminate order. */
// Path: src/main/java/net/worldline/training/angular/data/bookcat/Book.java // public class Book { // private String id; // private String name; // private String author; // // // // private Float price; // private String description; // private String category; // private boolean isNew; // private BookComment[] comments; // // public Book() { // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Float getPrice() { // return price; // } // // public void setPrice(float price) { // this.price = price; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setIsNew(boolean isNew) { // this.isNew = isNew; // } // // public boolean getIsNew() { // return isNew; // } // // public BookComment[] getComments() { // return comments; // } // // public void setComments(BookComment[] comments) { // this.comments = comments; // } // // // /*public JSONObject getJSONObject() { // String json=""; // ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); // JSONObject ret = new JSONObject(); // // ret.put("id",this.id); // ret.put("author",this.author); // ret.put("name",this.name); // ret.put("description",this.description); // ret.put("category",this.category); // ret.put("price",this.price); // ret.put("isNew",this.isNew); // // try { // // json = ow.writeValueAsString(this.comments); // ret.put("comments",new JSONArray(json)); // // } catch (IOException e) { // e.printStackTrace(); // } // catch (Exception e) { // e.printStackTrace(); // } // // return ret; // // }*/ // } // Path: src/main/java/net/worldline/training/angular/services/BookCatalog.java import java.util.List; import net.worldline.training.angular.data.bookcat.Book; package net.worldline.training.angular.services; public interface BookCatalog { /** * Provides a list of all phone in an indeterminate order. */
List<Book> getBooks();
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/ws/service/AccountService.java
// Path: src/main/java/net/worldline/training/angular/entity/User.java // @Entity // public class User implements Serializable // { // private static final long serialVersionUID = 1L; // @Transient // private int id; // private String uri; // private String firstName; // private String lastName; // private Date lastModified; // private String email; // @Id // private String login; // private String password; // @ElementCollection // @CollectionTable(name="Roles", joinColumns=@JoinColumn(name="user_login")) // @Column(name="roles") // private List<String> roles; // // public User() {} // // public Date getLastModified() { // return lastModified; // } // public void setLastModified(Date lastModified) { // this.lastModified = lastModified; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getUri() { // return uri; // } // public void setUri(String uri) { // this.uri = uri; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getLogin() { // return login; // } // public void setLogin(String login) { // this.login = login; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public List<String> getRoles() { // return roles; // } // public void setRoles(List<String> roles) { // this.roles = roles; // } // }
import net.worldline.training.angular.entity.User; import net.worldline.training.angular.services.UserDAO; import org.apache.tapestry5.ioc.annotations.Inject; import javax.annotation.security.PermitAll; import javax.ws.rs.*; import javax.ws.rs.core.Response;
package net.worldline.training.angular.ws.service; @Path("/app/account") public class AccountService { @Inject UserDAO userDatabase; @POST @Path("/register") @Consumes("application/json") @PermitAll
// Path: src/main/java/net/worldline/training/angular/entity/User.java // @Entity // public class User implements Serializable // { // private static final long serialVersionUID = 1L; // @Transient // private int id; // private String uri; // private String firstName; // private String lastName; // private Date lastModified; // private String email; // @Id // private String login; // private String password; // @ElementCollection // @CollectionTable(name="Roles", joinColumns=@JoinColumn(name="user_login")) // @Column(name="roles") // private List<String> roles; // // public User() {} // // public Date getLastModified() { // return lastModified; // } // public void setLastModified(Date lastModified) { // this.lastModified = lastModified; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getUri() { // return uri; // } // public void setUri(String uri) { // this.uri = uri; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getLogin() { // return login; // } // public void setLogin(String login) { // this.login = login; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public List<String> getRoles() { // return roles; // } // public void setRoles(List<String> roles) { // this.roles = roles; // } // } // Path: src/main/java/net/worldline/training/angular/ws/service/AccountService.java import net.worldline.training.angular.entity.User; import net.worldline.training.angular.services.UserDAO; import org.apache.tapestry5.ioc.annotations.Inject; import javax.annotation.security.PermitAll; import javax.ws.rs.*; import javax.ws.rs.core.Response; package net.worldline.training.angular.ws.service; @Path("/app/account") public class AccountService { @Inject UserDAO userDatabase; @POST @Path("/register") @Consumes("application/json") @PermitAll
public Response addUser(User newUser) {
worldline/TrainingJEEAngularJS
src/test/java/net/worldline/training/angular/pages/TestIndex.java
// Path: src/main/java/net/worldline/training/angular/pages/Index.java // @Import(stylesheet={"context:/bookcat/style/k-structure.css", // "context:/bookcat/style/k-theme0.css", // "context:/bookcat/style/style.css"}) // public class Index // { // // // }
import junit.framework.Assert; import org.apache.tapestry5.dom.Document; import org.apache.tapestry5.test.PageTester; import org.junit.Test; import net.worldline.training.angular.pages.Index;
/** * Simple JUnit test with the PageTester. */ package net.worldline.training.angular.pages; public class TestIndex extends Assert { /** * Test if the page contains id = color and if the text inside this id is * the same as defined in constant. */ @Test public final void test() { String appPackage = "net.worldline.training.angular"; String appName = "App"; PageTester tester = new PageTester(appPackage, appName, "src/main/webapp");
// Path: src/main/java/net/worldline/training/angular/pages/Index.java // @Import(stylesheet={"context:/bookcat/style/k-structure.css", // "context:/bookcat/style/k-theme0.css", // "context:/bookcat/style/style.css"}) // public class Index // { // // // } // Path: src/test/java/net/worldline/training/angular/pages/TestIndex.java import junit.framework.Assert; import org.apache.tapestry5.dom.Document; import org.apache.tapestry5.test.PageTester; import org.junit.Test; import net.worldline.training.angular.pages.Index; /** * Simple JUnit test with the PageTester. */ package net.worldline.training.angular.pages; public class TestIndex extends Assert { /** * Test if the page contains id = color and if the text inside this id is * the same as defined in constant. */ @Test public final void test() { String appPackage = "net.worldline.training.angular"; String appName = "App"; PageTester tester = new PageTester(appPackage, appName, "src/main/webapp");
Document doc = tester.renderPage("Index");
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/ws/service/UserService.java
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/data/user/RoleEnum.java // public enum RoleEnum { // ALL(RoleConsts.ALL_ROLE), ADMIN(RoleConsts.ADMIN_ROLE), USER(RoleConsts.USER_ROLE); // // private String role; // // private RoleEnum(String s) { // role = s; // } // // public String getRole() { // return role; // } // // } // // Path: src/main/java/net/worldline/training/angular/entity/User.java // @Entity // public class User implements Serializable // { // private static final long serialVersionUID = 1L; // @Transient // private int id; // private String uri; // private String firstName; // private String lastName; // private Date lastModified; // private String email; // @Id // private String login; // private String password; // @ElementCollection // @CollectionTable(name="Roles", joinColumns=@JoinColumn(name="user_login")) // @Column(name="roles") // private List<String> roles; // // public User() {} // // public Date getLastModified() { // return lastModified; // } // public void setLastModified(Date lastModified) { // this.lastModified = lastModified; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getUri() { // return uri; // } // public void setUri(String uri) { // this.uri = uri; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getLogin() { // return login; // } // public void setLogin(String login) { // this.login = login; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public List<String> getRoles() { // return roles; // } // public void setRoles(List<String> roles) { // this.roles = roles; // } // }
import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.data.user.RoleEnum; import net.worldline.training.angular.data.user.Token; import net.worldline.training.angular.entity.User; import net.worldline.training.angular.services.UserDAO; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.json.JSONObject; import org.jboss.resteasy.util.Base64; import org.slf4j.Logger; import org.tynamo.security.services.SecurityService; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.*;
package net.worldline.training.angular.ws.service; @Path("/app/user") public class UserService { private static final String AUTHORIZATION_PROPERTY = "Authorization"; private static final String AUTHENTICATION_SCHEME = "Basic"; @Inject private UserDAO userDatabase; @Inject private SecurityService securityService; @Inject private Logger LOG; @GET @Path("/users/{login}") @PermitAll public Response getUserByLogin(@PathParam("login") String login, @Context Request req) { Response.ResponseBuilder rb = Response.ok(userDatabase.getUserByLogin(login)); return rb.build(); } @PUT @Path("/users/{login}")
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/data/user/RoleEnum.java // public enum RoleEnum { // ALL(RoleConsts.ALL_ROLE), ADMIN(RoleConsts.ADMIN_ROLE), USER(RoleConsts.USER_ROLE); // // private String role; // // private RoleEnum(String s) { // role = s; // } // // public String getRole() { // return role; // } // // } // // Path: src/main/java/net/worldline/training/angular/entity/User.java // @Entity // public class User implements Serializable // { // private static final long serialVersionUID = 1L; // @Transient // private int id; // private String uri; // private String firstName; // private String lastName; // private Date lastModified; // private String email; // @Id // private String login; // private String password; // @ElementCollection // @CollectionTable(name="Roles", joinColumns=@JoinColumn(name="user_login")) // @Column(name="roles") // private List<String> roles; // // public User() {} // // public Date getLastModified() { // return lastModified; // } // public void setLastModified(Date lastModified) { // this.lastModified = lastModified; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getUri() { // return uri; // } // public void setUri(String uri) { // this.uri = uri; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getLogin() { // return login; // } // public void setLogin(String login) { // this.login = login; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public List<String> getRoles() { // return roles; // } // public void setRoles(List<String> roles) { // this.roles = roles; // } // } // Path: src/main/java/net/worldline/training/angular/ws/service/UserService.java import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.data.user.RoleEnum; import net.worldline.training.angular.data.user.Token; import net.worldline.training.angular.entity.User; import net.worldline.training.angular.services.UserDAO; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.json.JSONObject; import org.jboss.resteasy.util.Base64; import org.slf4j.Logger; import org.tynamo.security.services.SecurityService; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.*; package net.worldline.training.angular.ws.service; @Path("/app/user") public class UserService { private static final String AUTHORIZATION_PROPERTY = "Authorization"; private static final String AUTHENTICATION_SCHEME = "Basic"; @Inject private UserDAO userDatabase; @Inject private SecurityService securityService; @Inject private Logger LOG; @GET @Path("/users/{login}") @PermitAll public Response getUserByLogin(@PathParam("login") String login, @Context Request req) { Response.ResponseBuilder rb = Response.ok(userDatabase.getUserByLogin(login)); return rb.build(); } @PUT @Path("/users/{login}")
@RolesAllowed(RoleConsts.ADMIN_ROLE)
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/ws/service/UserService.java
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/data/user/RoleEnum.java // public enum RoleEnum { // ALL(RoleConsts.ALL_ROLE), ADMIN(RoleConsts.ADMIN_ROLE), USER(RoleConsts.USER_ROLE); // // private String role; // // private RoleEnum(String s) { // role = s; // } // // public String getRole() { // return role; // } // // } // // Path: src/main/java/net/worldline/training/angular/entity/User.java // @Entity // public class User implements Serializable // { // private static final long serialVersionUID = 1L; // @Transient // private int id; // private String uri; // private String firstName; // private String lastName; // private Date lastModified; // private String email; // @Id // private String login; // private String password; // @ElementCollection // @CollectionTable(name="Roles", joinColumns=@JoinColumn(name="user_login")) // @Column(name="roles") // private List<String> roles; // // public User() {} // // public Date getLastModified() { // return lastModified; // } // public void setLastModified(Date lastModified) { // this.lastModified = lastModified; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getUri() { // return uri; // } // public void setUri(String uri) { // this.uri = uri; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getLogin() { // return login; // } // public void setLogin(String login) { // this.login = login; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public List<String> getRoles() { // return roles; // } // public void setRoles(List<String> roles) { // this.roles = roles; // } // }
import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.data.user.RoleEnum; import net.worldline.training.angular.data.user.Token; import net.worldline.training.angular.entity.User; import net.worldline.training.angular.services.UserDAO; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.json.JSONObject; import org.jboss.resteasy.util.Base64; import org.slf4j.Logger; import org.tynamo.security.services.SecurityService; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.*;
package net.worldline.training.angular.ws.service; @Path("/app/user") public class UserService { private static final String AUTHORIZATION_PROPERTY = "Authorization"; private static final String AUTHENTICATION_SCHEME = "Basic"; @Inject private UserDAO userDatabase; @Inject private SecurityService securityService; @Inject private Logger LOG; @GET @Path("/users/{login}") @PermitAll public Response getUserByLogin(@PathParam("login") String login, @Context Request req) { Response.ResponseBuilder rb = Response.ok(userDatabase.getUserByLogin(login)); return rb.build(); } @PUT @Path("/users/{login}") @RolesAllowed(RoleConsts.ADMIN_ROLE) public Response updateUserById(@PathParam("login") String login) { //Update the User resource
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/data/user/RoleEnum.java // public enum RoleEnum { // ALL(RoleConsts.ALL_ROLE), ADMIN(RoleConsts.ADMIN_ROLE), USER(RoleConsts.USER_ROLE); // // private String role; // // private RoleEnum(String s) { // role = s; // } // // public String getRole() { // return role; // } // // } // // Path: src/main/java/net/worldline/training/angular/entity/User.java // @Entity // public class User implements Serializable // { // private static final long serialVersionUID = 1L; // @Transient // private int id; // private String uri; // private String firstName; // private String lastName; // private Date lastModified; // private String email; // @Id // private String login; // private String password; // @ElementCollection // @CollectionTable(name="Roles", joinColumns=@JoinColumn(name="user_login")) // @Column(name="roles") // private List<String> roles; // // public User() {} // // public Date getLastModified() { // return lastModified; // } // public void setLastModified(Date lastModified) { // this.lastModified = lastModified; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getUri() { // return uri; // } // public void setUri(String uri) { // this.uri = uri; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getLogin() { // return login; // } // public void setLogin(String login) { // this.login = login; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public List<String> getRoles() { // return roles; // } // public void setRoles(List<String> roles) { // this.roles = roles; // } // } // Path: src/main/java/net/worldline/training/angular/ws/service/UserService.java import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.data.user.RoleEnum; import net.worldline.training.angular.data.user.Token; import net.worldline.training.angular.entity.User; import net.worldline.training.angular.services.UserDAO; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.json.JSONObject; import org.jboss.resteasy.util.Base64; import org.slf4j.Logger; import org.tynamo.security.services.SecurityService; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.*; package net.worldline.training.angular.ws.service; @Path("/app/user") public class UserService { private static final String AUTHORIZATION_PROPERTY = "Authorization"; private static final String AUTHENTICATION_SCHEME = "Basic"; @Inject private UserDAO userDatabase; @Inject private SecurityService securityService; @Inject private Logger LOG; @GET @Path("/users/{login}") @PermitAll public Response getUserByLogin(@PathParam("login") String login, @Context Request req) { Response.ResponseBuilder rb = Response.ok(userDatabase.getUserByLogin(login)); return rb.build(); } @PUT @Path("/users/{login}") @RolesAllowed(RoleConsts.ADMIN_ROLE) public Response updateUserById(@PathParam("login") String login) { //Update the User resource
User user=userDatabase.getUserByLogin(login);
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/ws/service/UserService.java
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/data/user/RoleEnum.java // public enum RoleEnum { // ALL(RoleConsts.ALL_ROLE), ADMIN(RoleConsts.ADMIN_ROLE), USER(RoleConsts.USER_ROLE); // // private String role; // // private RoleEnum(String s) { // role = s; // } // // public String getRole() { // return role; // } // // } // // Path: src/main/java/net/worldline/training/angular/entity/User.java // @Entity // public class User implements Serializable // { // private static final long serialVersionUID = 1L; // @Transient // private int id; // private String uri; // private String firstName; // private String lastName; // private Date lastModified; // private String email; // @Id // private String login; // private String password; // @ElementCollection // @CollectionTable(name="Roles", joinColumns=@JoinColumn(name="user_login")) // @Column(name="roles") // private List<String> roles; // // public User() {} // // public Date getLastModified() { // return lastModified; // } // public void setLastModified(Date lastModified) { // this.lastModified = lastModified; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getUri() { // return uri; // } // public void setUri(String uri) { // this.uri = uri; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getLogin() { // return login; // } // public void setLogin(String login) { // this.login = login; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public List<String> getRoles() { // return roles; // } // public void setRoles(List<String> roles) { // this.roles = roles; // } // }
import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.data.user.RoleEnum; import net.worldline.training.angular.data.user.Token; import net.worldline.training.angular.entity.User; import net.worldline.training.angular.services.UserDAO; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.json.JSONObject; import org.jboss.resteasy.util.Base64; import org.slf4j.Logger; import org.tynamo.security.services.SecurityService; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.*;
usernameAndPassword = new String(Base64.decode(encodedUserPassword)); } catch (IOException e) { JSONEntity.put("message","invalid token"); return Response.status(Response.Status.BAD_REQUEST).entity(JSONEntity.toString()).build(); } //Split username and password tokens final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); final String username = tokenizer.nextToken(); final String password = tokenizer.nextToken(); Subject subject; try { subject = securityService.getSubject(); if (!subject.isAuthenticated()) { JSONEntity.put("message","not authenticated"); return Response.status(Response.Status.BAD_REQUEST).entity(JSONEntity.toString()).build(); } String userNameFromSubject = subject.getPrincipal().toString(); if(!userNameFromSubject.equals(username)){ JSONEntity.put("message","invalid user or password"); return Response.status(Response.Status.BAD_REQUEST).entity(JSONEntity.toString()).build(); } User user = new User(); user.setLogin(userNameFromSubject); List<String> roles = new ArrayList<String>() ;
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/data/user/RoleEnum.java // public enum RoleEnum { // ALL(RoleConsts.ALL_ROLE), ADMIN(RoleConsts.ADMIN_ROLE), USER(RoleConsts.USER_ROLE); // // private String role; // // private RoleEnum(String s) { // role = s; // } // // public String getRole() { // return role; // } // // } // // Path: src/main/java/net/worldline/training/angular/entity/User.java // @Entity // public class User implements Serializable // { // private static final long serialVersionUID = 1L; // @Transient // private int id; // private String uri; // private String firstName; // private String lastName; // private Date lastModified; // private String email; // @Id // private String login; // private String password; // @ElementCollection // @CollectionTable(name="Roles", joinColumns=@JoinColumn(name="user_login")) // @Column(name="roles") // private List<String> roles; // // public User() {} // // public Date getLastModified() { // return lastModified; // } // public void setLastModified(Date lastModified) { // this.lastModified = lastModified; // } // public int getId() { // return id; // } // public void setId(int id) { // this.id = id; // } // public String getFirstName() { // return firstName; // } // public void setFirstName(String firstName) { // this.firstName = firstName; // } // public String getLastName() { // return lastName; // } // public void setLastName(String lastName) { // this.lastName = lastName; // } // public String getUri() { // return uri; // } // public void setUri(String uri) { // this.uri = uri; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // public String getLogin() { // return login; // } // public void setLogin(String login) { // this.login = login; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public List<String> getRoles() { // return roles; // } // public void setRoles(List<String> roles) { // this.roles = roles; // } // } // Path: src/main/java/net/worldline/training/angular/ws/service/UserService.java import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.data.user.RoleEnum; import net.worldline.training.angular.data.user.Token; import net.worldline.training.angular.entity.User; import net.worldline.training.angular.services.UserDAO; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.json.JSONObject; import org.jboss.resteasy.util.Base64; import org.slf4j.Logger; import org.tynamo.security.services.SecurityService; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import java.io.IOException; import java.util.*; usernameAndPassword = new String(Base64.decode(encodedUserPassword)); } catch (IOException e) { JSONEntity.put("message","invalid token"); return Response.status(Response.Status.BAD_REQUEST).entity(JSONEntity.toString()).build(); } //Split username and password tokens final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); final String username = tokenizer.nextToken(); final String password = tokenizer.nextToken(); Subject subject; try { subject = securityService.getSubject(); if (!subject.isAuthenticated()) { JSONEntity.put("message","not authenticated"); return Response.status(Response.Status.BAD_REQUEST).entity(JSONEntity.toString()).build(); } String userNameFromSubject = subject.getPrincipal().toString(); if(!userNameFromSubject.equals(username)){ JSONEntity.put("message","invalid user or password"); return Response.status(Response.Status.BAD_REQUEST).entity(JSONEntity.toString()).build(); } User user = new User(); user.setLogin(userNameFromSubject); List<String> roles = new ArrayList<String>() ;
for (RoleEnum r: RoleEnum.values())
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/services/PhoneCatalogImpl.java
// Path: src/main/java/net/worldline/training/angular/data/phonecat/Phone.java // public class Phone { // // int age; // String carrier; // String id; // String imageUrl; // String name; // String snippet; // // public Phone(int age,String id,String imageUrl,String name,String snippet) // { // this.age = age; // this.id = id; // this.imageUrl = imageUrl; // this.name = name; // this.snippet = snippet; // } // // public Phone() // { // } // // // public long getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSnippet() { // return snippet; // } // // public void setSnippet(String snippet) { // this.snippet = snippet; // } // // public String getCarrier() { // return carrier; // } // // public void setCarrier(String carrier) { // this.carrier = carrier; // } // }
import java.io.*; import java.util.Hashtable; import java.util.List; import net.worldline.training.angular.data.phonecat.Phone; import net.worldline.training.angular.data.phonecat.PhoneDetails; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference;
package net.worldline.training.angular.services; public class PhoneCatalogImpl implements PhoneCatalog {
// Path: src/main/java/net/worldline/training/angular/data/phonecat/Phone.java // public class Phone { // // int age; // String carrier; // String id; // String imageUrl; // String name; // String snippet; // // public Phone(int age,String id,String imageUrl,String name,String snippet) // { // this.age = age; // this.id = id; // this.imageUrl = imageUrl; // this.name = name; // this.snippet = snippet; // } // // public Phone() // { // } // // // public long getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getSnippet() { // return snippet; // } // // public void setSnippet(String snippet) { // this.snippet = snippet; // } // // public String getCarrier() { // return carrier; // } // // public void setCarrier(String carrier) { // this.carrier = carrier; // } // } // Path: src/main/java/net/worldline/training/angular/services/PhoneCatalogImpl.java import java.io.*; import java.util.Hashtable; import java.util.List; import net.worldline.training.angular.data.phonecat.Phone; import net.worldline.training.angular.data.phonecat.PhoneDetails; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; package net.worldline.training.angular.services; public class PhoneCatalogImpl implements PhoneCatalog {
private List<Phone> catalog;
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/ws/service/ProductResource.java
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/entity/Comment.java // @Entity // public class Comment { // // private String phoneId; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public Comment() { // } // // // public String getPhoneId() { // return phoneId; // } // // public void setPhoneId(String phoneId) { // this.phoneId = phoneId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // }
import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.entity.Comment; import net.worldline.training.angular.services.CommentDAO; import net.worldline.training.angular.services.PhoneCatalog; import org.apache.tapestry5.ioc.annotations.Inject; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.util.List;
package net.worldline.training.angular.ws.service; @Path("/json/phone") public class ProductResource { @Inject PhoneCatalog phoneCatalog; @Inject CommentDAO comments; @POST @Path("/comments") @Consumes("application/json")
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/entity/Comment.java // @Entity // public class Comment { // // private String phoneId; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public Comment() { // } // // // public String getPhoneId() { // return phoneId; // } // // public void setPhoneId(String phoneId) { // this.phoneId = phoneId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // } // Path: src/main/java/net/worldline/training/angular/ws/service/ProductResource.java import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.entity.Comment; import net.worldline.training.angular.services.CommentDAO; import net.worldline.training.angular.services.PhoneCatalog; import org.apache.tapestry5.ioc.annotations.Inject; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.util.List; package net.worldline.training.angular.ws.service; @Path("/json/phone") public class ProductResource { @Inject PhoneCatalog phoneCatalog; @Inject CommentDAO comments; @POST @Path("/comments") @Consumes("application/json")
@RolesAllowed(RoleConsts.USER_ROLE)
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/ws/service/ProductResource.java
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/entity/Comment.java // @Entity // public class Comment { // // private String phoneId; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public Comment() { // } // // // public String getPhoneId() { // return phoneId; // } // // public void setPhoneId(String phoneId) { // this.phoneId = phoneId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // }
import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.entity.Comment; import net.worldline.training.angular.services.CommentDAO; import net.worldline.training.angular.services.PhoneCatalog; import org.apache.tapestry5.ioc.annotations.Inject; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.util.List;
package net.worldline.training.angular.ws.service; @Path("/json/phone") public class ProductResource { @Inject PhoneCatalog phoneCatalog; @Inject CommentDAO comments; @POST @Path("/comments") @Consumes("application/json") @RolesAllowed(RoleConsts.USER_ROLE)
// Path: src/main/java/net/worldline/training/angular/data/user/RoleConsts.java // public final class RoleConsts { // // public static final String ALL_ROLE = "*"; // public static final String USER_ROLE = "USER"; // public static final String ADMIN_ROLE = "ADMIN"; // // } // // Path: src/main/java/net/worldline/training/angular/entity/Comment.java // @Entity // public class Comment { // // private String phoneId; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public Comment() { // } // // // public String getPhoneId() { // return phoneId; // } // // public void setPhoneId(String phoneId) { // this.phoneId = phoneId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // } // Path: src/main/java/net/worldline/training/angular/ws/service/ProductResource.java import net.worldline.training.angular.data.user.RoleConsts; import net.worldline.training.angular.entity.Comment; import net.worldline.training.angular.services.CommentDAO; import net.worldline.training.angular.services.PhoneCatalog; import org.apache.tapestry5.ioc.annotations.Inject; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.util.List; package net.worldline.training.angular.ws.service; @Path("/json/phone") public class ProductResource { @Inject PhoneCatalog phoneCatalog; @Inject CommentDAO comments; @POST @Path("/comments") @Consumes("application/json") @RolesAllowed(RoleConsts.USER_ROLE)
public Response postComment(Comment comment) {
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/services/CommentDAOImpl.java
// Path: src/main/java/net/worldline/training/angular/entity/Comment.java // @Entity // public class Comment { // // private String phoneId; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public Comment() { // } // // // public String getPhoneId() { // return phoneId; // } // // public void setPhoneId(String phoneId) { // this.phoneId = phoneId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // }
import net.worldline.training.angular.entity.Comment; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import java.util.List;
package net.worldline.training.angular.services; public class CommentDAOImpl implements CommentDAO { private final Session session; public CommentDAOImpl(Session session) { this.session = session; }
// Path: src/main/java/net/worldline/training/angular/entity/Comment.java // @Entity // public class Comment { // // private String phoneId; // private String author; // private String content; // private int likes; // @Id // @GeneratedValue(strategy= GenerationType.IDENTITY) // private int id; // // public Comment() { // } // // // public String getPhoneId() { // return phoneId; // } // // public void setPhoneId(String phoneId) { // this.phoneId = phoneId; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public int getLikes() { // return likes; // } // // public void setLikes(int likes) { // this.likes = likes; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // } // Path: src/main/java/net/worldline/training/angular/services/CommentDAOImpl.java import net.worldline.training.angular.entity.Comment; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import java.util.List; package net.worldline.training.angular.services; public class CommentDAOImpl implements CommentDAO { private final Session session; public CommentDAOImpl(Session session) { this.session = session; }
public List<Comment> getCommentsByPhoneId(String phoneId) {
worldline/TrainingJEEAngularJS
src/main/java/net/worldline/training/angular/data/bookcat/Book.java
// Path: src/main/java/net/worldline/training/angular/data/bookcat/BookComment.java // public class BookComment { // // // private String user; // private String comment; // private int rate; // // public BookComment() { // } // // // // public String getUser() { // return user; // } // // public void setUser(String author) { // this.user = author; // } // // public String getComment() { // return comment; // } // // public void setComment(String content) { // this.comment = content; // } // // public int getRate() { // return rate; // } // // public void setRate(int rate) { // this.rate = rate; // } // // }
import net.worldline.training.angular.data.bookcat.BookComment; import org.apache.tapestry5.json.JSONArray; import org.apache.tapestry5.json.JSONObject; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectWriter; import java.io.IOException;
package net.worldline.training.angular.data.bookcat; public class Book { private String id; private String name; private String author; private Float price; private String description; private String category; private boolean isNew;
// Path: src/main/java/net/worldline/training/angular/data/bookcat/BookComment.java // public class BookComment { // // // private String user; // private String comment; // private int rate; // // public BookComment() { // } // // // // public String getUser() { // return user; // } // // public void setUser(String author) { // this.user = author; // } // // public String getComment() { // return comment; // } // // public void setComment(String content) { // this.comment = content; // } // // public int getRate() { // return rate; // } // // public void setRate(int rate) { // this.rate = rate; // } // // } // Path: src/main/java/net/worldline/training/angular/data/bookcat/Book.java import net.worldline.training.angular.data.bookcat.BookComment; import org.apache.tapestry5.json.JSONArray; import org.apache.tapestry5.json.JSONObject; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectWriter; import java.io.IOException; package net.worldline.training.angular.data.bookcat; public class Book { private String id; private String name; private String author; private Float price; private String description; private String category; private boolean isNew;
private BookComment[] comments;
idega/is.idega.idegaweb.msi
src/java/is/idega/idegaweb/msi/presentation/EventEditor.java
// Path: src/java/is/idega/idegaweb/msi/MsiConstants.java // public class MsiConstants { // public static final String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.msi"; // } // // Path: src/java/is/idega/idegaweb/msi/data/Event.java // public interface Event extends IDOEntity { // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#getPrimaryKeyClass // */ // public Class getPrimaryKeyClass(); // // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#getName // */ // public String getName(); // // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#setName // */ // public void setName(String name); // // public boolean isValid(); // // public void setValid(boolean valid); // } // // Path: src/java/is/idega/idegaweb/msi/data/EventHome.java // public interface EventHome extends IDOHome { // public Event create() throws CreateException; // // public Event findByPrimaryKey(Object pk) throws FinderException; // // public Collection findAll() throws FinderException; // public Collection getInvalidEvents(); // }
import is.idega.idegaweb.msi.MsiConstants; import is.idega.idegaweb.msi.data.Event; import is.idega.idegaweb.msi.data.EventHome; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import javax.ejb.CreateException; import javax.ejb.FinderException; import com.idega.block.web2.business.Web2Business; import com.idega.business.IBOLookup; import com.idega.data.IDOLookup; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWMainApplication; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.Table2; import com.idega.presentation.TableCell2; import com.idega.presentation.TableRow; import com.idega.presentation.TableRowGroup; import com.idega.presentation.text.Break; import com.idega.presentation.text.Text; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.Label; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextInput; import com.idega.util.CoreConstants; import com.idega.util.CoreUtil; import com.idega.util.PresentationUtil;
row.createHeaderCell(); cell = row.createHeaderCell(); cell.add(new Text(localize("event_editor.unactive_events", "Unactive events"))); group = table.createBodyRowGroup(); row = group.createRow(); cell = row.createCell(); Layer activeEvents = new Layer("select"); cell.add(activeEvents); activeEvents.setStyleClass("events-selector active-events"); activeEvents.setMarkupAttribute("multiple", "multiple"); cell = row.createCell(); Layer disable = new Layer("input"); cell.add(disable); disable.setMarkupAttribute("type", "button"); disable.setMarkupAttribute("value", ">>"); disable.setStyleClass("action disable"); Layer enable = new Layer("input"); cell.add(enable); enable.setMarkupAttribute("type", "button"); enable.setStyleClass("action enable"); enable.setMarkupAttribute("value", "<<"); cell = row.createCell(); Layer inactiveEvents = new Layer("select"); cell.add(inactiveEvents); inactiveEvents.setStyleClass("events-selector inactive-events"); inactiveEvents.setMarkupAttribute("multiple", "multiple"); for (Iterator iter = events.iterator();iter.hasNext();) {
// Path: src/java/is/idega/idegaweb/msi/MsiConstants.java // public class MsiConstants { // public static final String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.msi"; // } // // Path: src/java/is/idega/idegaweb/msi/data/Event.java // public interface Event extends IDOEntity { // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#getPrimaryKeyClass // */ // public Class getPrimaryKeyClass(); // // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#getName // */ // public String getName(); // // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#setName // */ // public void setName(String name); // // public boolean isValid(); // // public void setValid(boolean valid); // } // // Path: src/java/is/idega/idegaweb/msi/data/EventHome.java // public interface EventHome extends IDOHome { // public Event create() throws CreateException; // // public Event findByPrimaryKey(Object pk) throws FinderException; // // public Collection findAll() throws FinderException; // public Collection getInvalidEvents(); // } // Path: src/java/is/idega/idegaweb/msi/presentation/EventEditor.java import is.idega.idegaweb.msi.MsiConstants; import is.idega.idegaweb.msi.data.Event; import is.idega.idegaweb.msi.data.EventHome; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import javax.ejb.CreateException; import javax.ejb.FinderException; import com.idega.block.web2.business.Web2Business; import com.idega.business.IBOLookup; import com.idega.data.IDOLookup; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWMainApplication; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.Table2; import com.idega.presentation.TableCell2; import com.idega.presentation.TableRow; import com.idega.presentation.TableRowGroup; import com.idega.presentation.text.Break; import com.idega.presentation.text.Text; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.Label; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextInput; import com.idega.util.CoreConstants; import com.idega.util.CoreUtil; import com.idega.util.PresentationUtil; row.createHeaderCell(); cell = row.createHeaderCell(); cell.add(new Text(localize("event_editor.unactive_events", "Unactive events"))); group = table.createBodyRowGroup(); row = group.createRow(); cell = row.createCell(); Layer activeEvents = new Layer("select"); cell.add(activeEvents); activeEvents.setStyleClass("events-selector active-events"); activeEvents.setMarkupAttribute("multiple", "multiple"); cell = row.createCell(); Layer disable = new Layer("input"); cell.add(disable); disable.setMarkupAttribute("type", "button"); disable.setMarkupAttribute("value", ">>"); disable.setStyleClass("action disable"); Layer enable = new Layer("input"); cell.add(enable); enable.setMarkupAttribute("type", "button"); enable.setStyleClass("action enable"); enable.setMarkupAttribute("value", "<<"); cell = row.createCell(); Layer inactiveEvents = new Layer("select"); cell.add(inactiveEvents); inactiveEvents.setStyleClass("events-selector inactive-events"); inactiveEvents.setMarkupAttribute("multiple", "multiple"); for (Iterator iter = events.iterator();iter.hasNext();) {
Event event = (Event) iter.next();
idega/is.idega.idegaweb.msi
src/java/is/idega/idegaweb/msi/presentation/EventEditor.java
// Path: src/java/is/idega/idegaweb/msi/MsiConstants.java // public class MsiConstants { // public static final String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.msi"; // } // // Path: src/java/is/idega/idegaweb/msi/data/Event.java // public interface Event extends IDOEntity { // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#getPrimaryKeyClass // */ // public Class getPrimaryKeyClass(); // // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#getName // */ // public String getName(); // // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#setName // */ // public void setName(String name); // // public boolean isValid(); // // public void setValid(boolean valid); // } // // Path: src/java/is/idega/idegaweb/msi/data/EventHome.java // public interface EventHome extends IDOHome { // public Event create() throws CreateException; // // public Event findByPrimaryKey(Object pk) throws FinderException; // // public Collection findAll() throws FinderException; // public Collection getInvalidEvents(); // }
import is.idega.idegaweb.msi.MsiConstants; import is.idega.idegaweb.msi.data.Event; import is.idega.idegaweb.msi.data.EventHome; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import javax.ejb.CreateException; import javax.ejb.FinderException; import com.idega.block.web2.business.Web2Business; import com.idega.business.IBOLookup; import com.idega.data.IDOLookup; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWMainApplication; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.Table2; import com.idega.presentation.TableCell2; import com.idega.presentation.TableRow; import com.idega.presentation.TableRowGroup; import com.idega.presentation.text.Break; import com.idega.presentation.text.Text; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.Label; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextInput; import com.idega.util.CoreConstants; import com.idega.util.CoreUtil; import com.idega.util.PresentationUtil;
Layer activeEvents = new Layer("select"); cell.add(activeEvents); activeEvents.setStyleClass("events-selector active-events"); activeEvents.setMarkupAttribute("multiple", "multiple"); cell = row.createCell(); Layer disable = new Layer("input"); cell.add(disable); disable.setMarkupAttribute("type", "button"); disable.setMarkupAttribute("value", ">>"); disable.setStyleClass("action disable"); Layer enable = new Layer("input"); cell.add(enable); enable.setMarkupAttribute("type", "button"); enable.setStyleClass("action enable"); enable.setMarkupAttribute("value", "<<"); cell = row.createCell(); Layer inactiveEvents = new Layer("select"); cell.add(inactiveEvents); inactiveEvents.setStyleClass("events-selector inactive-events"); inactiveEvents.setMarkupAttribute("multiple", "multiple"); for (Iterator iter = events.iterator();iter.hasNext();) { Event event = (Event) iter.next(); Layer option = new Layer("option"); activeEvents.add(option); option.setMarkupAttribute("value", event.getPrimaryKey().toString()); row = group.createRow(); option.add(event.getName()); }
// Path: src/java/is/idega/idegaweb/msi/MsiConstants.java // public class MsiConstants { // public static final String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.msi"; // } // // Path: src/java/is/idega/idegaweb/msi/data/Event.java // public interface Event extends IDOEntity { // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#getPrimaryKeyClass // */ // public Class getPrimaryKeyClass(); // // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#getName // */ // public String getName(); // // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#setName // */ // public void setName(String name); // // public boolean isValid(); // // public void setValid(boolean valid); // } // // Path: src/java/is/idega/idegaweb/msi/data/EventHome.java // public interface EventHome extends IDOHome { // public Event create() throws CreateException; // // public Event findByPrimaryKey(Object pk) throws FinderException; // // public Collection findAll() throws FinderException; // public Collection getInvalidEvents(); // } // Path: src/java/is/idega/idegaweb/msi/presentation/EventEditor.java import is.idega.idegaweb.msi.MsiConstants; import is.idega.idegaweb.msi.data.Event; import is.idega.idegaweb.msi.data.EventHome; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import javax.ejb.CreateException; import javax.ejb.FinderException; import com.idega.block.web2.business.Web2Business; import com.idega.business.IBOLookup; import com.idega.data.IDOLookup; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWMainApplication; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.Table2; import com.idega.presentation.TableCell2; import com.idega.presentation.TableRow; import com.idega.presentation.TableRowGroup; import com.idega.presentation.text.Break; import com.idega.presentation.text.Text; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.Label; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextInput; import com.idega.util.CoreConstants; import com.idega.util.CoreUtil; import com.idega.util.PresentationUtil; Layer activeEvents = new Layer("select"); cell.add(activeEvents); activeEvents.setStyleClass("events-selector active-events"); activeEvents.setMarkupAttribute("multiple", "multiple"); cell = row.createCell(); Layer disable = new Layer("input"); cell.add(disable); disable.setMarkupAttribute("type", "button"); disable.setMarkupAttribute("value", ">>"); disable.setStyleClass("action disable"); Layer enable = new Layer("input"); cell.add(enable); enable.setMarkupAttribute("type", "button"); enable.setStyleClass("action enable"); enable.setMarkupAttribute("value", "<<"); cell = row.createCell(); Layer inactiveEvents = new Layer("select"); cell.add(inactiveEvents); inactiveEvents.setStyleClass("events-selector inactive-events"); inactiveEvents.setMarkupAttribute("multiple", "multiple"); for (Iterator iter = events.iterator();iter.hasNext();) { Event event = (Event) iter.next(); Layer option = new Layer("option"); activeEvents.add(option); option.setMarkupAttribute("value", event.getPrimaryKey().toString()); row = group.createRow(); option.add(event.getName()); }
EventHome eventHome = (EventHome) IDOLookup.getHome(Event.class);
idega/is.idega.idegaweb.msi
src/java/is/idega/idegaweb/msi/presentation/EventEditor.java
// Path: src/java/is/idega/idegaweb/msi/MsiConstants.java // public class MsiConstants { // public static final String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.msi"; // } // // Path: src/java/is/idega/idegaweb/msi/data/Event.java // public interface Event extends IDOEntity { // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#getPrimaryKeyClass // */ // public Class getPrimaryKeyClass(); // // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#getName // */ // public String getName(); // // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#setName // */ // public void setName(String name); // // public boolean isValid(); // // public void setValid(boolean valid); // } // // Path: src/java/is/idega/idegaweb/msi/data/EventHome.java // public interface EventHome extends IDOHome { // public Event create() throws CreateException; // // public Event findByPrimaryKey(Object pk) throws FinderException; // // public Collection findAll() throws FinderException; // public Collection getInvalidEvents(); // }
import is.idega.idegaweb.msi.MsiConstants; import is.idega.idegaweb.msi.data.Event; import is.idega.idegaweb.msi.data.EventHome; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import javax.ejb.CreateException; import javax.ejb.FinderException; import com.idega.block.web2.business.Web2Business; import com.idega.business.IBOLookup; import com.idega.data.IDOLookup; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWMainApplication; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.Table2; import com.idega.presentation.TableCell2; import com.idega.presentation.TableRow; import com.idega.presentation.TableRowGroup; import com.idega.presentation.text.Break; import com.idega.presentation.text.Text; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.Label; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextInput; import com.idega.util.CoreConstants; import com.idega.util.CoreUtil; import com.idega.util.PresentationUtil;
option.setMarkupAttribute("value", event.getPrimaryKey().toString()); row = group.createRow(); option.add(event.getName()); } EventHome eventHome = (EventHome) IDOLookup.getHome(Event.class); events = eventHome.getInvalidEvents(); for (Iterator iter = events.iterator();iter.hasNext();) { Event event = (Event) iter.next(); Layer option = new Layer("option"); inactiveEvents.add(option); option.setMarkupAttribute("value", event.getPrimaryKey().toString()); row = group.createRow(); option.add(event.getName()); } form.add(table); form.add(new Break()); SubmitButton newLink = (SubmitButton) getButton(new SubmitButton(localize("event_editor.new_event", "New event"), PARAMETER_ACTION, String.valueOf(ACTION_NEW))); form.add(newLink); add(form); addFiles(iwc); StringBuilder script = new StringBuilder("jQuery(document).ready(function(){jQuery('#").append(table.getId()).append("').eventsEditor();});"); Layer scriptTag = new Layer("script"); form.add(scriptTag); scriptTag.add(script.toString()); } private void addFiles(IWContext iwc){ IWMainApplication iwma = iwc.getApplicationContext().getIWMainApplication();
// Path: src/java/is/idega/idegaweb/msi/MsiConstants.java // public class MsiConstants { // public static final String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.msi"; // } // // Path: src/java/is/idega/idegaweb/msi/data/Event.java // public interface Event extends IDOEntity { // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#getPrimaryKeyClass // */ // public Class getPrimaryKeyClass(); // // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#getName // */ // public String getName(); // // /** // * @see is.idega.idegaweb.msi.data.EventBMPBean#setName // */ // public void setName(String name); // // public boolean isValid(); // // public void setValid(boolean valid); // } // // Path: src/java/is/idega/idegaweb/msi/data/EventHome.java // public interface EventHome extends IDOHome { // public Event create() throws CreateException; // // public Event findByPrimaryKey(Object pk) throws FinderException; // // public Collection findAll() throws FinderException; // public Collection getInvalidEvents(); // } // Path: src/java/is/idega/idegaweb/msi/presentation/EventEditor.java import is.idega.idegaweb.msi.MsiConstants; import is.idega.idegaweb.msi.data.Event; import is.idega.idegaweb.msi.data.EventHome; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import javax.ejb.CreateException; import javax.ejb.FinderException; import com.idega.block.web2.business.Web2Business; import com.idega.business.IBOLookup; import com.idega.data.IDOLookup; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWMainApplication; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.Table2; import com.idega.presentation.TableCell2; import com.idega.presentation.TableRow; import com.idega.presentation.TableRowGroup; import com.idega.presentation.text.Break; import com.idega.presentation.text.Text; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.Label; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextInput; import com.idega.util.CoreConstants; import com.idega.util.CoreUtil; import com.idega.util.PresentationUtil; option.setMarkupAttribute("value", event.getPrimaryKey().toString()); row = group.createRow(); option.add(event.getName()); } EventHome eventHome = (EventHome) IDOLookup.getHome(Event.class); events = eventHome.getInvalidEvents(); for (Iterator iter = events.iterator();iter.hasNext();) { Event event = (Event) iter.next(); Layer option = new Layer("option"); inactiveEvents.add(option); option.setMarkupAttribute("value", event.getPrimaryKey().toString()); row = group.createRow(); option.add(event.getName()); } form.add(table); form.add(new Break()); SubmitButton newLink = (SubmitButton) getButton(new SubmitButton(localize("event_editor.new_event", "New event"), PARAMETER_ACTION, String.valueOf(ACTION_NEW))); form.add(newLink); add(form); addFiles(iwc); StringBuilder script = new StringBuilder("jQuery(document).ready(function(){jQuery('#").append(table.getId()).append("').eventsEditor();});"); Layer scriptTag = new Layer("script"); form.add(scriptTag); scriptTag.add(script.toString()); } private void addFiles(IWContext iwc){ IWMainApplication iwma = iwc.getApplicationContext().getIWMainApplication();
IWBundle iwb = iwma.getBundle(MsiConstants.IW_BUNDLE_IDENTIFIER);
idega/is.idega.idegaweb.msi
src/java/is/idega/idegaweb/msi/business/RaceDateComparator.java
// Path: src/java/is/idega/idegaweb/msi/data/Race.java // public interface Race extends IDOEntity, Group { // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#getRaceDate // */ // public Timestamp getRaceDate(); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#getLastRegistrationDate // */ // public Timestamp getLastRegistrationDate(); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#getLastRegistrationDatePrice1 // */ // public Timestamp getLastRegistrationDatePrice1(); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#getChipRent // */ // public float getChipRent(); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#getRaceCategory // */ // public RaceCategory getRaceCategory(); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#getRaceType // */ // public RaceType getRaceType(); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setRaceDate // */ // public void setRaceDate(Timestamp date); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setLastRegistrationDate // */ // public void setLastRegistrationDate(Timestamp date); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setLastRegistrationDatePrice1 // */ // public void setLastRegistrationDatePrice1(Timestamp date); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setChipRent // */ // public void setChipRent(float rent); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setRaceCategory // */ // public void setRaceCategory(RaceCategory raceCategory); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setRaceCategory // */ // public void setRaceCategory(String raceCategoryID); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setRaceType // */ // public void setRaceType(RaceType raceType); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setRaceType // */ // public void setRaceType(String raceTypeID); // }
import is.idega.idegaweb.msi.data.Race; import java.util.Comparator; import com.idega.util.IWTimestamp;
package is.idega.idegaweb.msi.business; public class RaceDateComparator implements Comparator { public RaceDateComparator() { super(); } /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(Object o1, Object o2) {
// Path: src/java/is/idega/idegaweb/msi/data/Race.java // public interface Race extends IDOEntity, Group { // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#getRaceDate // */ // public Timestamp getRaceDate(); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#getLastRegistrationDate // */ // public Timestamp getLastRegistrationDate(); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#getLastRegistrationDatePrice1 // */ // public Timestamp getLastRegistrationDatePrice1(); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#getChipRent // */ // public float getChipRent(); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#getRaceCategory // */ // public RaceCategory getRaceCategory(); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#getRaceType // */ // public RaceType getRaceType(); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setRaceDate // */ // public void setRaceDate(Timestamp date); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setLastRegistrationDate // */ // public void setLastRegistrationDate(Timestamp date); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setLastRegistrationDatePrice1 // */ // public void setLastRegistrationDatePrice1(Timestamp date); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setChipRent // */ // public void setChipRent(float rent); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setRaceCategory // */ // public void setRaceCategory(RaceCategory raceCategory); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setRaceCategory // */ // public void setRaceCategory(String raceCategoryID); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setRaceType // */ // public void setRaceType(RaceType raceType); // // /** // * @see is.idega.idegaweb.msi.data.RaceBMPBean#setRaceType // */ // public void setRaceType(String raceTypeID); // } // Path: src/java/is/idega/idegaweb/msi/business/RaceDateComparator.java import is.idega.idegaweb.msi.data.Race; import java.util.Comparator; import com.idega.util.IWTimestamp; package is.idega.idegaweb.msi.business; public class RaceDateComparator implements Comparator { public RaceDateComparator() { super(); } /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(Object o1, Object o2) {
Race r1 = (Race) o1;
NymphWeb/nymph
com/nymph/bean/web/WebApplicationBeansFactory.java
// Path: com/nymph/bean/BeansComponent.java // public interface BeansComponent { // /** // * 根据注解类型获取组件Bean // * @param anno 指定的注解 // * @return 对应的bean组件 // */ // Optional<Object> getComponent(Class<? extends Annotation> anno); // // /** // * 获取拦截器链 // * @return // */ // List<Interceptors> getInterceptors(); // /** // * 过滤出组件的Bean // * @param bean bean实例 // */ // void filter(Object bean); // // } // // Path: com/nymph/bean/BeansFactory.java // public interface BeansFactory { // /** // * 将bean注册到容器中 // */ // void register(); // /** // * 根据bean的名字获取到bean的实例 // * @param beanName bean的名字, 一般为bean的类名 // * @return 这个bean的实例 // */ // Object getBean(String beanName); // /** // * 根据bean的类型来获取到bean的实例 // * @param beanClass bean的类型 // * @return bean的实例 // */ // <T> T getBean(Class<T> beanClass); // /** // * 获取bean工厂的所有bean实例 // * @return bean实例的集合 // */ // Collection<?> getBeans(); // } // // Path: com/nymph/bean/BeansHandler.java // public interface BeansHandler { // /** // * 在注册到bean容器之前的处理 // * @param beansClass bean的实例 // * @return 表示最终要存入容器的对象 // * @throws Exception // */ // Object handlerBefore(Object bean); // /** // * 在注册到bean容器之后的处理 // * @param bean bean的实例 // */ // void handlerAfter(Object bean); // // } // // Path: com/nymph/bean/BeansProxy.java // public interface BeansProxy { // /** // * Jdk的动态代理, 可以在此返回代理对象注册到bean工厂 // * @param bean bean的实例 // * @return 代理后的对象 // */ // Object proxyBean(Object bean); // // } // // Path: com/nymph/config/Configuration.java // public class Configuration { // // xml的组件配置 // private List<Object> component; // // 关于web的配置 // private WebConfig webConfig; // // 关于包扫描的配置 // private List<String> scanner; // // 指定bean处理器 // private String beansHandler; // // public Optional<String> getBeansHandler() { // return Optional.ofNullable(beansHandler); // } // // public void setBeansHandler(String beansHandler) { // this.beansHandler = beansHandler; // } // // public WebConfig getWebConfig() { // return webConfig; // } // // public void setWebConfig(WebConfig webConfig) { // this.webConfig = webConfig; // } // // public List<String> getScanner() { // return scanner == null ? Collections.emptyList() : scanner; // } // // public void setScanner(List<String> scanner) { // this.scanner = scanner; // } // // public List<Object> getComponent() { // return component == null ? Collections.emptyList() : component; // } // // public void setComponent(List<Object> component) { // this.component = component; // } // // public void addConfiguration(Configuration configuration) { // if (component == null) { // component = new ArrayList<>(); // component.addAll(configuration.getComponent()); // } else { // component.addAll(configuration.getComponent()); // } // } // // }
import com.nymph.bean.BeansComponent; import com.nymph.bean.BeansFactory; import com.nymph.bean.BeansHandler; import com.nymph.bean.BeansProxy; import com.nymph.config.Configuration;
package com.nymph.bean.web; /** * web应用必须的Bean工厂 * @author LiuYang * @author LiangTianDong * @date 2017年10月23日上午11:32:44 */ public interface WebApplicationBeansFactory extends BeansFactory { /** * 获取HttpBean处理器 * @return */ MapperInfoContainer getHttpBeansContainer(); /** * plain setter * @param httpHandler HttpBean处理器 */ void setHttpBeansContainer(MapperInfoContainer httpHandler); /** * 获取基础的Bean处理器 * @return */
// Path: com/nymph/bean/BeansComponent.java // public interface BeansComponent { // /** // * 根据注解类型获取组件Bean // * @param anno 指定的注解 // * @return 对应的bean组件 // */ // Optional<Object> getComponent(Class<? extends Annotation> anno); // // /** // * 获取拦截器链 // * @return // */ // List<Interceptors> getInterceptors(); // /** // * 过滤出组件的Bean // * @param bean bean实例 // */ // void filter(Object bean); // // } // // Path: com/nymph/bean/BeansFactory.java // public interface BeansFactory { // /** // * 将bean注册到容器中 // */ // void register(); // /** // * 根据bean的名字获取到bean的实例 // * @param beanName bean的名字, 一般为bean的类名 // * @return 这个bean的实例 // */ // Object getBean(String beanName); // /** // * 根据bean的类型来获取到bean的实例 // * @param beanClass bean的类型 // * @return bean的实例 // */ // <T> T getBean(Class<T> beanClass); // /** // * 获取bean工厂的所有bean实例 // * @return bean实例的集合 // */ // Collection<?> getBeans(); // } // // Path: com/nymph/bean/BeansHandler.java // public interface BeansHandler { // /** // * 在注册到bean容器之前的处理 // * @param beansClass bean的实例 // * @return 表示最终要存入容器的对象 // * @throws Exception // */ // Object handlerBefore(Object bean); // /** // * 在注册到bean容器之后的处理 // * @param bean bean的实例 // */ // void handlerAfter(Object bean); // // } // // Path: com/nymph/bean/BeansProxy.java // public interface BeansProxy { // /** // * Jdk的动态代理, 可以在此返回代理对象注册到bean工厂 // * @param bean bean的实例 // * @return 代理后的对象 // */ // Object proxyBean(Object bean); // // } // // Path: com/nymph/config/Configuration.java // public class Configuration { // // xml的组件配置 // private List<Object> component; // // 关于web的配置 // private WebConfig webConfig; // // 关于包扫描的配置 // private List<String> scanner; // // 指定bean处理器 // private String beansHandler; // // public Optional<String> getBeansHandler() { // return Optional.ofNullable(beansHandler); // } // // public void setBeansHandler(String beansHandler) { // this.beansHandler = beansHandler; // } // // public WebConfig getWebConfig() { // return webConfig; // } // // public void setWebConfig(WebConfig webConfig) { // this.webConfig = webConfig; // } // // public List<String> getScanner() { // return scanner == null ? Collections.emptyList() : scanner; // } // // public void setScanner(List<String> scanner) { // this.scanner = scanner; // } // // public List<Object> getComponent() { // return component == null ? Collections.emptyList() : component; // } // // public void setComponent(List<Object> component) { // this.component = component; // } // // public void addConfiguration(Configuration configuration) { // if (component == null) { // component = new ArrayList<>(); // component.addAll(configuration.getComponent()); // } else { // component.addAll(configuration.getComponent()); // } // } // // } // Path: com/nymph/bean/web/WebApplicationBeansFactory.java import com.nymph.bean.BeansComponent; import com.nymph.bean.BeansFactory; import com.nymph.bean.BeansHandler; import com.nymph.bean.BeansProxy; import com.nymph.config.Configuration; package com.nymph.bean.web; /** * web应用必须的Bean工厂 * @author LiuYang * @author LiangTianDong * @date 2017年10月23日上午11:32:44 */ public interface WebApplicationBeansFactory extends BeansFactory { /** * 获取HttpBean处理器 * @return */ MapperInfoContainer getHttpBeansContainer(); /** * plain setter * @param httpHandler HttpBean处理器 */ void setHttpBeansContainer(MapperInfoContainer httpHandler); /** * 获取基础的Bean处理器 * @return */
BeansHandler getBeansHandler();
NymphWeb/nymph
com/nymph/bean/web/WebApplicationBeansFactory.java
// Path: com/nymph/bean/BeansComponent.java // public interface BeansComponent { // /** // * 根据注解类型获取组件Bean // * @param anno 指定的注解 // * @return 对应的bean组件 // */ // Optional<Object> getComponent(Class<? extends Annotation> anno); // // /** // * 获取拦截器链 // * @return // */ // List<Interceptors> getInterceptors(); // /** // * 过滤出组件的Bean // * @param bean bean实例 // */ // void filter(Object bean); // // } // // Path: com/nymph/bean/BeansFactory.java // public interface BeansFactory { // /** // * 将bean注册到容器中 // */ // void register(); // /** // * 根据bean的名字获取到bean的实例 // * @param beanName bean的名字, 一般为bean的类名 // * @return 这个bean的实例 // */ // Object getBean(String beanName); // /** // * 根据bean的类型来获取到bean的实例 // * @param beanClass bean的类型 // * @return bean的实例 // */ // <T> T getBean(Class<T> beanClass); // /** // * 获取bean工厂的所有bean实例 // * @return bean实例的集合 // */ // Collection<?> getBeans(); // } // // Path: com/nymph/bean/BeansHandler.java // public interface BeansHandler { // /** // * 在注册到bean容器之前的处理 // * @param beansClass bean的实例 // * @return 表示最终要存入容器的对象 // * @throws Exception // */ // Object handlerBefore(Object bean); // /** // * 在注册到bean容器之后的处理 // * @param bean bean的实例 // */ // void handlerAfter(Object bean); // // } // // Path: com/nymph/bean/BeansProxy.java // public interface BeansProxy { // /** // * Jdk的动态代理, 可以在此返回代理对象注册到bean工厂 // * @param bean bean的实例 // * @return 代理后的对象 // */ // Object proxyBean(Object bean); // // } // // Path: com/nymph/config/Configuration.java // public class Configuration { // // xml的组件配置 // private List<Object> component; // // 关于web的配置 // private WebConfig webConfig; // // 关于包扫描的配置 // private List<String> scanner; // // 指定bean处理器 // private String beansHandler; // // public Optional<String> getBeansHandler() { // return Optional.ofNullable(beansHandler); // } // // public void setBeansHandler(String beansHandler) { // this.beansHandler = beansHandler; // } // // public WebConfig getWebConfig() { // return webConfig; // } // // public void setWebConfig(WebConfig webConfig) { // this.webConfig = webConfig; // } // // public List<String> getScanner() { // return scanner == null ? Collections.emptyList() : scanner; // } // // public void setScanner(List<String> scanner) { // this.scanner = scanner; // } // // public List<Object> getComponent() { // return component == null ? Collections.emptyList() : component; // } // // public void setComponent(List<Object> component) { // this.component = component; // } // // public void addConfiguration(Configuration configuration) { // if (component == null) { // component = new ArrayList<>(); // component.addAll(configuration.getComponent()); // } else { // component.addAll(configuration.getComponent()); // } // } // // }
import com.nymph.bean.BeansComponent; import com.nymph.bean.BeansFactory; import com.nymph.bean.BeansHandler; import com.nymph.bean.BeansProxy; import com.nymph.config.Configuration;
package com.nymph.bean.web; /** * web应用必须的Bean工厂 * @author LiuYang * @author LiangTianDong * @date 2017年10月23日上午11:32:44 */ public interface WebApplicationBeansFactory extends BeansFactory { /** * 获取HttpBean处理器 * @return */ MapperInfoContainer getHttpBeansContainer(); /** * plain setter * @param httpHandler HttpBean处理器 */ void setHttpBeansContainer(MapperInfoContainer httpHandler); /** * 获取基础的Bean处理器 * @return */ BeansHandler getBeansHandler(); /** * plain setter * @param beansHandler */ void setBeansHandler(BeansHandler beansHandler); /** * 获取配置对象 * @return */
// Path: com/nymph/bean/BeansComponent.java // public interface BeansComponent { // /** // * 根据注解类型获取组件Bean // * @param anno 指定的注解 // * @return 对应的bean组件 // */ // Optional<Object> getComponent(Class<? extends Annotation> anno); // // /** // * 获取拦截器链 // * @return // */ // List<Interceptors> getInterceptors(); // /** // * 过滤出组件的Bean // * @param bean bean实例 // */ // void filter(Object bean); // // } // // Path: com/nymph/bean/BeansFactory.java // public interface BeansFactory { // /** // * 将bean注册到容器中 // */ // void register(); // /** // * 根据bean的名字获取到bean的实例 // * @param beanName bean的名字, 一般为bean的类名 // * @return 这个bean的实例 // */ // Object getBean(String beanName); // /** // * 根据bean的类型来获取到bean的实例 // * @param beanClass bean的类型 // * @return bean的实例 // */ // <T> T getBean(Class<T> beanClass); // /** // * 获取bean工厂的所有bean实例 // * @return bean实例的集合 // */ // Collection<?> getBeans(); // } // // Path: com/nymph/bean/BeansHandler.java // public interface BeansHandler { // /** // * 在注册到bean容器之前的处理 // * @param beansClass bean的实例 // * @return 表示最终要存入容器的对象 // * @throws Exception // */ // Object handlerBefore(Object bean); // /** // * 在注册到bean容器之后的处理 // * @param bean bean的实例 // */ // void handlerAfter(Object bean); // // } // // Path: com/nymph/bean/BeansProxy.java // public interface BeansProxy { // /** // * Jdk的动态代理, 可以在此返回代理对象注册到bean工厂 // * @param bean bean的实例 // * @return 代理后的对象 // */ // Object proxyBean(Object bean); // // } // // Path: com/nymph/config/Configuration.java // public class Configuration { // // xml的组件配置 // private List<Object> component; // // 关于web的配置 // private WebConfig webConfig; // // 关于包扫描的配置 // private List<String> scanner; // // 指定bean处理器 // private String beansHandler; // // public Optional<String> getBeansHandler() { // return Optional.ofNullable(beansHandler); // } // // public void setBeansHandler(String beansHandler) { // this.beansHandler = beansHandler; // } // // public WebConfig getWebConfig() { // return webConfig; // } // // public void setWebConfig(WebConfig webConfig) { // this.webConfig = webConfig; // } // // public List<String> getScanner() { // return scanner == null ? Collections.emptyList() : scanner; // } // // public void setScanner(List<String> scanner) { // this.scanner = scanner; // } // // public List<Object> getComponent() { // return component == null ? Collections.emptyList() : component; // } // // public void setComponent(List<Object> component) { // this.component = component; // } // // public void addConfiguration(Configuration configuration) { // if (component == null) { // component = new ArrayList<>(); // component.addAll(configuration.getComponent()); // } else { // component.addAll(configuration.getComponent()); // } // } // // } // Path: com/nymph/bean/web/WebApplicationBeansFactory.java import com.nymph.bean.BeansComponent; import com.nymph.bean.BeansFactory; import com.nymph.bean.BeansHandler; import com.nymph.bean.BeansProxy; import com.nymph.config.Configuration; package com.nymph.bean.web; /** * web应用必须的Bean工厂 * @author LiuYang * @author LiangTianDong * @date 2017年10月23日上午11:32:44 */ public interface WebApplicationBeansFactory extends BeansFactory { /** * 获取HttpBean处理器 * @return */ MapperInfoContainer getHttpBeansContainer(); /** * plain setter * @param httpHandler HttpBean处理器 */ void setHttpBeansContainer(MapperInfoContainer httpHandler); /** * 获取基础的Bean处理器 * @return */ BeansHandler getBeansHandler(); /** * plain setter * @param beansHandler */ void setBeansHandler(BeansHandler beansHandler); /** * 获取配置对象 * @return */
Configuration getConfiguration();
NymphWeb/nymph
com/nymph/bean/web/WebApplicationBeansFactory.java
// Path: com/nymph/bean/BeansComponent.java // public interface BeansComponent { // /** // * 根据注解类型获取组件Bean // * @param anno 指定的注解 // * @return 对应的bean组件 // */ // Optional<Object> getComponent(Class<? extends Annotation> anno); // // /** // * 获取拦截器链 // * @return // */ // List<Interceptors> getInterceptors(); // /** // * 过滤出组件的Bean // * @param bean bean实例 // */ // void filter(Object bean); // // } // // Path: com/nymph/bean/BeansFactory.java // public interface BeansFactory { // /** // * 将bean注册到容器中 // */ // void register(); // /** // * 根据bean的名字获取到bean的实例 // * @param beanName bean的名字, 一般为bean的类名 // * @return 这个bean的实例 // */ // Object getBean(String beanName); // /** // * 根据bean的类型来获取到bean的实例 // * @param beanClass bean的类型 // * @return bean的实例 // */ // <T> T getBean(Class<T> beanClass); // /** // * 获取bean工厂的所有bean实例 // * @return bean实例的集合 // */ // Collection<?> getBeans(); // } // // Path: com/nymph/bean/BeansHandler.java // public interface BeansHandler { // /** // * 在注册到bean容器之前的处理 // * @param beansClass bean的实例 // * @return 表示最终要存入容器的对象 // * @throws Exception // */ // Object handlerBefore(Object bean); // /** // * 在注册到bean容器之后的处理 // * @param bean bean的实例 // */ // void handlerAfter(Object bean); // // } // // Path: com/nymph/bean/BeansProxy.java // public interface BeansProxy { // /** // * Jdk的动态代理, 可以在此返回代理对象注册到bean工厂 // * @param bean bean的实例 // * @return 代理后的对象 // */ // Object proxyBean(Object bean); // // } // // Path: com/nymph/config/Configuration.java // public class Configuration { // // xml的组件配置 // private List<Object> component; // // 关于web的配置 // private WebConfig webConfig; // // 关于包扫描的配置 // private List<String> scanner; // // 指定bean处理器 // private String beansHandler; // // public Optional<String> getBeansHandler() { // return Optional.ofNullable(beansHandler); // } // // public void setBeansHandler(String beansHandler) { // this.beansHandler = beansHandler; // } // // public WebConfig getWebConfig() { // return webConfig; // } // // public void setWebConfig(WebConfig webConfig) { // this.webConfig = webConfig; // } // // public List<String> getScanner() { // return scanner == null ? Collections.emptyList() : scanner; // } // // public void setScanner(List<String> scanner) { // this.scanner = scanner; // } // // public List<Object> getComponent() { // return component == null ? Collections.emptyList() : component; // } // // public void setComponent(List<Object> component) { // this.component = component; // } // // public void addConfiguration(Configuration configuration) { // if (component == null) { // component = new ArrayList<>(); // component.addAll(configuration.getComponent()); // } else { // component.addAll(configuration.getComponent()); // } // } // // }
import com.nymph.bean.BeansComponent; import com.nymph.bean.BeansFactory; import com.nymph.bean.BeansHandler; import com.nymph.bean.BeansProxy; import com.nymph.config.Configuration;
package com.nymph.bean.web; /** * web应用必须的Bean工厂 * @author LiuYang * @author LiangTianDong * @date 2017年10月23日上午11:32:44 */ public interface WebApplicationBeansFactory extends BeansFactory { /** * 获取HttpBean处理器 * @return */ MapperInfoContainer getHttpBeansContainer(); /** * plain setter * @param httpHandler HttpBean处理器 */ void setHttpBeansContainer(MapperInfoContainer httpHandler); /** * 获取基础的Bean处理器 * @return */ BeansHandler getBeansHandler(); /** * plain setter * @param beansHandler */ void setBeansHandler(BeansHandler beansHandler); /** * 获取配置对象 * @return */ Configuration getConfiguration(); /** * 设置配置对象 */ void setConfiguration(Configuration Configuration); /** * 获取bean组件对象 * @return */
// Path: com/nymph/bean/BeansComponent.java // public interface BeansComponent { // /** // * 根据注解类型获取组件Bean // * @param anno 指定的注解 // * @return 对应的bean组件 // */ // Optional<Object> getComponent(Class<? extends Annotation> anno); // // /** // * 获取拦截器链 // * @return // */ // List<Interceptors> getInterceptors(); // /** // * 过滤出组件的Bean // * @param bean bean实例 // */ // void filter(Object bean); // // } // // Path: com/nymph/bean/BeansFactory.java // public interface BeansFactory { // /** // * 将bean注册到容器中 // */ // void register(); // /** // * 根据bean的名字获取到bean的实例 // * @param beanName bean的名字, 一般为bean的类名 // * @return 这个bean的实例 // */ // Object getBean(String beanName); // /** // * 根据bean的类型来获取到bean的实例 // * @param beanClass bean的类型 // * @return bean的实例 // */ // <T> T getBean(Class<T> beanClass); // /** // * 获取bean工厂的所有bean实例 // * @return bean实例的集合 // */ // Collection<?> getBeans(); // } // // Path: com/nymph/bean/BeansHandler.java // public interface BeansHandler { // /** // * 在注册到bean容器之前的处理 // * @param beansClass bean的实例 // * @return 表示最终要存入容器的对象 // * @throws Exception // */ // Object handlerBefore(Object bean); // /** // * 在注册到bean容器之后的处理 // * @param bean bean的实例 // */ // void handlerAfter(Object bean); // // } // // Path: com/nymph/bean/BeansProxy.java // public interface BeansProxy { // /** // * Jdk的动态代理, 可以在此返回代理对象注册到bean工厂 // * @param bean bean的实例 // * @return 代理后的对象 // */ // Object proxyBean(Object bean); // // } // // Path: com/nymph/config/Configuration.java // public class Configuration { // // xml的组件配置 // private List<Object> component; // // 关于web的配置 // private WebConfig webConfig; // // 关于包扫描的配置 // private List<String> scanner; // // 指定bean处理器 // private String beansHandler; // // public Optional<String> getBeansHandler() { // return Optional.ofNullable(beansHandler); // } // // public void setBeansHandler(String beansHandler) { // this.beansHandler = beansHandler; // } // // public WebConfig getWebConfig() { // return webConfig; // } // // public void setWebConfig(WebConfig webConfig) { // this.webConfig = webConfig; // } // // public List<String> getScanner() { // return scanner == null ? Collections.emptyList() : scanner; // } // // public void setScanner(List<String> scanner) { // this.scanner = scanner; // } // // public List<Object> getComponent() { // return component == null ? Collections.emptyList() : component; // } // // public void setComponent(List<Object> component) { // this.component = component; // } // // public void addConfiguration(Configuration configuration) { // if (component == null) { // component = new ArrayList<>(); // component.addAll(configuration.getComponent()); // } else { // component.addAll(configuration.getComponent()); // } // } // // } // Path: com/nymph/bean/web/WebApplicationBeansFactory.java import com.nymph.bean.BeansComponent; import com.nymph.bean.BeansFactory; import com.nymph.bean.BeansHandler; import com.nymph.bean.BeansProxy; import com.nymph.config.Configuration; package com.nymph.bean.web; /** * web应用必须的Bean工厂 * @author LiuYang * @author LiangTianDong * @date 2017年10月23日上午11:32:44 */ public interface WebApplicationBeansFactory extends BeansFactory { /** * 获取HttpBean处理器 * @return */ MapperInfoContainer getHttpBeansContainer(); /** * plain setter * @param httpHandler HttpBean处理器 */ void setHttpBeansContainer(MapperInfoContainer httpHandler); /** * 获取基础的Bean处理器 * @return */ BeansHandler getBeansHandler(); /** * plain setter * @param beansHandler */ void setBeansHandler(BeansHandler beansHandler); /** * 获取配置对象 * @return */ Configuration getConfiguration(); /** * 设置配置对象 */ void setConfiguration(Configuration Configuration); /** * 获取bean组件对象 * @return */
BeansComponent getBeansComponent();
NymphWeb/nymph
com/nymph/context/core/ResovlerUrl.java
// Path: com/nymph/bean/web/MapperInfoContainer.java // public class MapperInfo implements Cloneable { // // web层映射类的类名 // private String name; // // 路径对应的方法 // private Method method; // // @UrlVal注解的value值 // private Map<String, String> placeHolder; // // public MapperInfo(String name, Method method) { // this.name = name; // this.method = method; // } // // public MapperInfo() {} // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Method getMethod() { // return method; // } // // public void setMethod(Method method) { // this.method = method; // } // // public Map<String, String> getPlaceHolder() { // return placeHolder; // } // // public void setPlaceHolder(Map<String, String> placeHolder) { // this.placeHolder = placeHolder; // } // // public MapperInfo initialize(Map<String, String> placeHolder) throws CloneNotSupportedException { // MapperInfo httpBean = (MapperInfo)this.clone(); // httpBean.setPlaceHolder(placeHolder); // return httpBean; // } // }
import java.util.Map; import com.nymph.bean.web.MapperInfoContainer.MapperInfo;
package com.nymph.context.core; /** * url解析器接口 * @author NYMPH * @date 2017年9月26日2017年9月26日 */ public interface ResovlerUrl extends Resolver{ /** * 当Content-Type为上传文件的类型时进行的处理 * @return 请求中所有参数的map * @throws Exception FileUploadExcaption异常, 和UnsupportedEncodingException编码异常 */ Map<String, String[]> multipartHandler() throws Exception; /** * 寻找和指定url匹配的类映射信息, 这里需要考虑是否使用了@PlaceHolder占位符注解, 如果没有则直接从HttpBeanContainer * 中获取, 否则需要遍历整个容器来寻找是否有对应的HttpBean, 并且需要获取到@PlaceHolder的value方法对应的值 * @param url 浏览器输入的url * @return url映射信息对象 * @throws Exception 这里使用到了clone, 可能抛出克隆方法的异常 */
// Path: com/nymph/bean/web/MapperInfoContainer.java // public class MapperInfo implements Cloneable { // // web层映射类的类名 // private String name; // // 路径对应的方法 // private Method method; // // @UrlVal注解的value值 // private Map<String, String> placeHolder; // // public MapperInfo(String name, Method method) { // this.name = name; // this.method = method; // } // // public MapperInfo() {} // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Method getMethod() { // return method; // } // // public void setMethod(Method method) { // this.method = method; // } // // public Map<String, String> getPlaceHolder() { // return placeHolder; // } // // public void setPlaceHolder(Map<String, String> placeHolder) { // this.placeHolder = placeHolder; // } // // public MapperInfo initialize(Map<String, String> placeHolder) throws CloneNotSupportedException { // MapperInfo httpBean = (MapperInfo)this.clone(); // httpBean.setPlaceHolder(placeHolder); // return httpBean; // } // } // Path: com/nymph/context/core/ResovlerUrl.java import java.util.Map; import com.nymph.bean.web.MapperInfoContainer.MapperInfo; package com.nymph.context.core; /** * url解析器接口 * @author NYMPH * @date 2017年9月26日2017年9月26日 */ public interface ResovlerUrl extends Resolver{ /** * 当Content-Type为上传文件的类型时进行的处理 * @return 请求中所有参数的map * @throws Exception FileUploadExcaption异常, 和UnsupportedEncodingException编码异常 */ Map<String, String[]> multipartHandler() throws Exception; /** * 寻找和指定url匹配的类映射信息, 这里需要考虑是否使用了@PlaceHolder占位符注解, 如果没有则直接从HttpBeanContainer * 中获取, 否则需要遍历整个容器来寻找是否有对应的HttpBean, 并且需要获取到@PlaceHolder的value方法对应的值 * @param url 浏览器输入的url * @return url映射信息对象 * @throws Exception 这里使用到了clone, 可能抛出克隆方法的异常 */
MapperInfo placeHolderHandler(String url) throws Exception;
NymphWeb/nymph
com/test/TestProxy.java
// Path: com/nymph/bean/BeansProxy.java // public interface BeansProxy { // /** // * Jdk的动态代理, 可以在此返回代理对象注册到bean工厂 // * @param bean bean的实例 // * @return 代理后的对象 // */ // Object proxyBean(Object bean); // // } // // Path: com/nymph/bean/proxy/AopUtils.java // public abstract class AopUtils { // // /** // * 获取代理对象, jdk的代理对象只能强转成父类才能正常使用, 所以他必须实现一个接口 // * @param target 被代理的对象 // * @param h 代理的具体操作在此对象的invoke方法内进行 // * @return jdk的代理对象 // */ // public static Object getProxy(Object target, InvocationHandler h) { // Class<?>[] interfaces = target.getClass().getInterfaces(); // if (interfaces.length == 0) { // throw new IllegalArgumentException("目标对象必须实现至少一个接口"); // } // // return Proxy.newProxyInstance(BasicUtil.getDefaultClassLoad(), interfaces, h); // } // // /** // * 获取代理对象, jdk的代理对象只能强转成父类才能正常使用, 所以他必须实现一个接口 // * @param target 被代理的对象Class // * @param h 代理的具体操作在此对象的invoke方法内进行 // * @return jdk的代理对象 // */ // public static Object getProxy(Class<?> target, InvocationHandler h) { // Class<?>[] interfaces = null; // if (target.isInterface()) { // interfaces = new Class<?>[]{target}; // } // // if (interfaces == null) { // interfaces = target.getInterfaces(); // if (interfaces.length == 0) { // throw new IllegalArgumentException("target必须为接口或者接口的实现类"); // } // } // // return Proxy.newProxyInstance(BasicUtil.getDefaultClassLoad(), interfaces, h); // } // }
import com.nymph.annotation.ConfigurationBean; import com.nymph.bean.BeansProxy; import com.nymph.bean.component.EnableBeanProxyHandler; import com.nymph.bean.proxy.AopUtils;
package com.test; @EnableBeanProxyHandler public class TestProxy implements BeansProxy { @Override public Object proxyBean(Object bean) { if (bean.getClass().isAnnotationPresent(ConfigurationBean.class)) {
// Path: com/nymph/bean/BeansProxy.java // public interface BeansProxy { // /** // * Jdk的动态代理, 可以在此返回代理对象注册到bean工厂 // * @param bean bean的实例 // * @return 代理后的对象 // */ // Object proxyBean(Object bean); // // } // // Path: com/nymph/bean/proxy/AopUtils.java // public abstract class AopUtils { // // /** // * 获取代理对象, jdk的代理对象只能强转成父类才能正常使用, 所以他必须实现一个接口 // * @param target 被代理的对象 // * @param h 代理的具体操作在此对象的invoke方法内进行 // * @return jdk的代理对象 // */ // public static Object getProxy(Object target, InvocationHandler h) { // Class<?>[] interfaces = target.getClass().getInterfaces(); // if (interfaces.length == 0) { // throw new IllegalArgumentException("目标对象必须实现至少一个接口"); // } // // return Proxy.newProxyInstance(BasicUtil.getDefaultClassLoad(), interfaces, h); // } // // /** // * 获取代理对象, jdk的代理对象只能强转成父类才能正常使用, 所以他必须实现一个接口 // * @param target 被代理的对象Class // * @param h 代理的具体操作在此对象的invoke方法内进行 // * @return jdk的代理对象 // */ // public static Object getProxy(Class<?> target, InvocationHandler h) { // Class<?>[] interfaces = null; // if (target.isInterface()) { // interfaces = new Class<?>[]{target}; // } // // if (interfaces == null) { // interfaces = target.getInterfaces(); // if (interfaces.length == 0) { // throw new IllegalArgumentException("target必须为接口或者接口的实现类"); // } // } // // return Proxy.newProxyInstance(BasicUtil.getDefaultClassLoad(), interfaces, h); // } // } // Path: com/test/TestProxy.java import com.nymph.annotation.ConfigurationBean; import com.nymph.bean.BeansProxy; import com.nymph.bean.component.EnableBeanProxyHandler; import com.nymph.bean.proxy.AopUtils; package com.test; @EnableBeanProxyHandler public class TestProxy implements BeansProxy { @Override public Object proxyBean(Object bean) { if (bean.getClass().isAnnotationPresent(ConfigurationBean.class)) {
return AopUtils.getProxy(bean, (o, m, r, p)->{
NymphWeb/nymph
com/nymph/context/ContextParameter.java
// Path: com/nymph/bean/web/MapperInfoContainer.java // public class MapperInfo implements Cloneable { // // web层映射类的类名 // private String name; // // 路径对应的方法 // private Method method; // // @UrlVal注解的value值 // private Map<String, String> placeHolder; // // public MapperInfo(String name, Method method) { // this.name = name; // this.method = method; // } // // public MapperInfo() {} // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Method getMethod() { // return method; // } // // public void setMethod(Method method) { // this.method = method; // } // // public Map<String, String> getPlaceHolder() { // return placeHolder; // } // // public void setPlaceHolder(Map<String, String> placeHolder) { // this.placeHolder = placeHolder; // } // // public MapperInfo initialize(Map<String, String> placeHolder) throws CloneNotSupportedException { // MapperInfo httpBean = (MapperInfo)this.clone(); // httpBean.setPlaceHolder(placeHolder); // return httpBean; // } // } // // Path: com/nymph/transfer/Multipart.java // public final class Multipart { // private static final Logger LOOGER = LoggerFactory.getLogger(Multipart.class); // // private final Map<String, FileInf> fileInfo = new HashMap<>(); // // public void addFiles(FileItem fileItem) { // try { // fileInfo.put(fileItem.getFieldName(), // new FileInf(fileItem.getName(), fileItem.getInputStream())); // } catch (Exception e) { // LOOGER.error(null, e); // } // } // // /** // * 通过页面input标签的name属性获取FileInf // * @param fieldName // * @return // */ // public FileInf getFileInf(String fieldName) { // return fileInfo.get(fieldName); // } // /** // * 页面的所有的type=file的input标签的name属性值 // * @return // */ // public List<String> fields() { // return fileInfo.keySet().stream().collect(Collectors.toList()); // } // /** // * 获取所有表示文件的FileInf // * @return // */ // public List<FileInf> fileInfs() { // return fileInfo.values().stream().collect(Collectors.toList()); // } // /** // * 根据input的name属性获取到对应的文件流 // * @param field // * @return // */ // public FileInputStream getInputStream(String field) { // return (FileInputStream)fileInfo.get(field).getStream(); // } // // public static class FileInf { // final String fileName; // // final InputStream input; // // public FileInf(String fileName, InputStream input) { // this.fileName = fileName; // this.input = input; // } // // public FileInputStream getStream() { // return (FileInputStream)input; // } // // /** // * 将文件写入到硬盘的指定位置 // * @param location 硬盘的地址 // * @return 写入完成后的文件 // */ // public File writeTo(String location) { // FileChannel channel = null; // FileOutputStream out = null; // try { // channel = getStream().getChannel(); // out = new FileOutputStream(location); // channel.transferTo(0, channel.size(), Channels.newChannel(out)); // return new File(location); // } catch (IOException e) { // LOOGER.error(null, e); // return null; // } finally { // BasicUtil.closed(channel, out); // } // } // // /** // * 上传的文件的真实名称 // * @return // */ // public String getFileName() { // return fileName; // } // // /** // * 根据name属性获取 上传的文件的后缀名 // * @return // */ // public String getFileSuffix() { // if (fileName.indexOf(".") < 0) { // return ""; // } // return fileName.substring(0, fileName.lastIndexOf(".")); // } // } // // }
import java.util.Map; import com.nymph.bean.web.MapperInfoContainer.MapperInfo; import com.nymph.transfer.Multipart;
package com.nymph.context; /** * 参数解析器将要解析的对象 * @author NYMPH * @date 2017年9月21日下午8:16:00 */ public class ContextParameter { private Map<String, String[]> params; private ContextWrapper context;
// Path: com/nymph/bean/web/MapperInfoContainer.java // public class MapperInfo implements Cloneable { // // web层映射类的类名 // private String name; // // 路径对应的方法 // private Method method; // // @UrlVal注解的value值 // private Map<String, String> placeHolder; // // public MapperInfo(String name, Method method) { // this.name = name; // this.method = method; // } // // public MapperInfo() {} // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Method getMethod() { // return method; // } // // public void setMethod(Method method) { // this.method = method; // } // // public Map<String, String> getPlaceHolder() { // return placeHolder; // } // // public void setPlaceHolder(Map<String, String> placeHolder) { // this.placeHolder = placeHolder; // } // // public MapperInfo initialize(Map<String, String> placeHolder) throws CloneNotSupportedException { // MapperInfo httpBean = (MapperInfo)this.clone(); // httpBean.setPlaceHolder(placeHolder); // return httpBean; // } // } // // Path: com/nymph/transfer/Multipart.java // public final class Multipart { // private static final Logger LOOGER = LoggerFactory.getLogger(Multipart.class); // // private final Map<String, FileInf> fileInfo = new HashMap<>(); // // public void addFiles(FileItem fileItem) { // try { // fileInfo.put(fileItem.getFieldName(), // new FileInf(fileItem.getName(), fileItem.getInputStream())); // } catch (Exception e) { // LOOGER.error(null, e); // } // } // // /** // * 通过页面input标签的name属性获取FileInf // * @param fieldName // * @return // */ // public FileInf getFileInf(String fieldName) { // return fileInfo.get(fieldName); // } // /** // * 页面的所有的type=file的input标签的name属性值 // * @return // */ // public List<String> fields() { // return fileInfo.keySet().stream().collect(Collectors.toList()); // } // /** // * 获取所有表示文件的FileInf // * @return // */ // public List<FileInf> fileInfs() { // return fileInfo.values().stream().collect(Collectors.toList()); // } // /** // * 根据input的name属性获取到对应的文件流 // * @param field // * @return // */ // public FileInputStream getInputStream(String field) { // return (FileInputStream)fileInfo.get(field).getStream(); // } // // public static class FileInf { // final String fileName; // // final InputStream input; // // public FileInf(String fileName, InputStream input) { // this.fileName = fileName; // this.input = input; // } // // public FileInputStream getStream() { // return (FileInputStream)input; // } // // /** // * 将文件写入到硬盘的指定位置 // * @param location 硬盘的地址 // * @return 写入完成后的文件 // */ // public File writeTo(String location) { // FileChannel channel = null; // FileOutputStream out = null; // try { // channel = getStream().getChannel(); // out = new FileOutputStream(location); // channel.transferTo(0, channel.size(), Channels.newChannel(out)); // return new File(location); // } catch (IOException e) { // LOOGER.error(null, e); // return null; // } finally { // BasicUtil.closed(channel, out); // } // } // // /** // * 上传的文件的真实名称 // * @return // */ // public String getFileName() { // return fileName; // } // // /** // * 根据name属性获取 上传的文件的后缀名 // * @return // */ // public String getFileSuffix() { // if (fileName.indexOf(".") < 0) { // return ""; // } // return fileName.substring(0, fileName.lastIndexOf(".")); // } // } // // } // Path: com/nymph/context/ContextParameter.java import java.util.Map; import com.nymph.bean.web.MapperInfoContainer.MapperInfo; import com.nymph.transfer.Multipart; package com.nymph.context; /** * 参数解析器将要解析的对象 * @author NYMPH * @date 2017年9月21日下午8:16:00 */ public class ContextParameter { private Map<String, String[]> params; private ContextWrapper context;
private Multipart multipart;
NymphWeb/nymph
com/nymph/context/ContextParameter.java
// Path: com/nymph/bean/web/MapperInfoContainer.java // public class MapperInfo implements Cloneable { // // web层映射类的类名 // private String name; // // 路径对应的方法 // private Method method; // // @UrlVal注解的value值 // private Map<String, String> placeHolder; // // public MapperInfo(String name, Method method) { // this.name = name; // this.method = method; // } // // public MapperInfo() {} // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Method getMethod() { // return method; // } // // public void setMethod(Method method) { // this.method = method; // } // // public Map<String, String> getPlaceHolder() { // return placeHolder; // } // // public void setPlaceHolder(Map<String, String> placeHolder) { // this.placeHolder = placeHolder; // } // // public MapperInfo initialize(Map<String, String> placeHolder) throws CloneNotSupportedException { // MapperInfo httpBean = (MapperInfo)this.clone(); // httpBean.setPlaceHolder(placeHolder); // return httpBean; // } // } // // Path: com/nymph/transfer/Multipart.java // public final class Multipart { // private static final Logger LOOGER = LoggerFactory.getLogger(Multipart.class); // // private final Map<String, FileInf> fileInfo = new HashMap<>(); // // public void addFiles(FileItem fileItem) { // try { // fileInfo.put(fileItem.getFieldName(), // new FileInf(fileItem.getName(), fileItem.getInputStream())); // } catch (Exception e) { // LOOGER.error(null, e); // } // } // // /** // * 通过页面input标签的name属性获取FileInf // * @param fieldName // * @return // */ // public FileInf getFileInf(String fieldName) { // return fileInfo.get(fieldName); // } // /** // * 页面的所有的type=file的input标签的name属性值 // * @return // */ // public List<String> fields() { // return fileInfo.keySet().stream().collect(Collectors.toList()); // } // /** // * 获取所有表示文件的FileInf // * @return // */ // public List<FileInf> fileInfs() { // return fileInfo.values().stream().collect(Collectors.toList()); // } // /** // * 根据input的name属性获取到对应的文件流 // * @param field // * @return // */ // public FileInputStream getInputStream(String field) { // return (FileInputStream)fileInfo.get(field).getStream(); // } // // public static class FileInf { // final String fileName; // // final InputStream input; // // public FileInf(String fileName, InputStream input) { // this.fileName = fileName; // this.input = input; // } // // public FileInputStream getStream() { // return (FileInputStream)input; // } // // /** // * 将文件写入到硬盘的指定位置 // * @param location 硬盘的地址 // * @return 写入完成后的文件 // */ // public File writeTo(String location) { // FileChannel channel = null; // FileOutputStream out = null; // try { // channel = getStream().getChannel(); // out = new FileOutputStream(location); // channel.transferTo(0, channel.size(), Channels.newChannel(out)); // return new File(location); // } catch (IOException e) { // LOOGER.error(null, e); // return null; // } finally { // BasicUtil.closed(channel, out); // } // } // // /** // * 上传的文件的真实名称 // * @return // */ // public String getFileName() { // return fileName; // } // // /** // * 根据name属性获取 上传的文件的后缀名 // * @return // */ // public String getFileSuffix() { // if (fileName.indexOf(".") < 0) { // return ""; // } // return fileName.substring(0, fileName.lastIndexOf(".")); // } // } // // }
import java.util.Map; import com.nymph.bean.web.MapperInfoContainer.MapperInfo; import com.nymph.transfer.Multipart;
package com.nymph.context; /** * 参数解析器将要解析的对象 * @author NYMPH * @date 2017年9月21日下午8:16:00 */ public class ContextParameter { private Map<String, String[]> params; private ContextWrapper context; private Multipart multipart;
// Path: com/nymph/bean/web/MapperInfoContainer.java // public class MapperInfo implements Cloneable { // // web层映射类的类名 // private String name; // // 路径对应的方法 // private Method method; // // @UrlVal注解的value值 // private Map<String, String> placeHolder; // // public MapperInfo(String name, Method method) { // this.name = name; // this.method = method; // } // // public MapperInfo() {} // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Method getMethod() { // return method; // } // // public void setMethod(Method method) { // this.method = method; // } // // public Map<String, String> getPlaceHolder() { // return placeHolder; // } // // public void setPlaceHolder(Map<String, String> placeHolder) { // this.placeHolder = placeHolder; // } // // public MapperInfo initialize(Map<String, String> placeHolder) throws CloneNotSupportedException { // MapperInfo httpBean = (MapperInfo)this.clone(); // httpBean.setPlaceHolder(placeHolder); // return httpBean; // } // } // // Path: com/nymph/transfer/Multipart.java // public final class Multipart { // private static final Logger LOOGER = LoggerFactory.getLogger(Multipart.class); // // private final Map<String, FileInf> fileInfo = new HashMap<>(); // // public void addFiles(FileItem fileItem) { // try { // fileInfo.put(fileItem.getFieldName(), // new FileInf(fileItem.getName(), fileItem.getInputStream())); // } catch (Exception e) { // LOOGER.error(null, e); // } // } // // /** // * 通过页面input标签的name属性获取FileInf // * @param fieldName // * @return // */ // public FileInf getFileInf(String fieldName) { // return fileInfo.get(fieldName); // } // /** // * 页面的所有的type=file的input标签的name属性值 // * @return // */ // public List<String> fields() { // return fileInfo.keySet().stream().collect(Collectors.toList()); // } // /** // * 获取所有表示文件的FileInf // * @return // */ // public List<FileInf> fileInfs() { // return fileInfo.values().stream().collect(Collectors.toList()); // } // /** // * 根据input的name属性获取到对应的文件流 // * @param field // * @return // */ // public FileInputStream getInputStream(String field) { // return (FileInputStream)fileInfo.get(field).getStream(); // } // // public static class FileInf { // final String fileName; // // final InputStream input; // // public FileInf(String fileName, InputStream input) { // this.fileName = fileName; // this.input = input; // } // // public FileInputStream getStream() { // return (FileInputStream)input; // } // // /** // * 将文件写入到硬盘的指定位置 // * @param location 硬盘的地址 // * @return 写入完成后的文件 // */ // public File writeTo(String location) { // FileChannel channel = null; // FileOutputStream out = null; // try { // channel = getStream().getChannel(); // out = new FileOutputStream(location); // channel.transferTo(0, channel.size(), Channels.newChannel(out)); // return new File(location); // } catch (IOException e) { // LOOGER.error(null, e); // return null; // } finally { // BasicUtil.closed(channel, out); // } // } // // /** // * 上传的文件的真实名称 // * @return // */ // public String getFileName() { // return fileName; // } // // /** // * 根据name属性获取 上传的文件的后缀名 // * @return // */ // public String getFileSuffix() { // if (fileName.indexOf(".") < 0) { // return ""; // } // return fileName.substring(0, fileName.lastIndexOf(".")); // } // } // // } // Path: com/nymph/context/ContextParameter.java import java.util.Map; import com.nymph.bean.web.MapperInfoContainer.MapperInfo; import com.nymph.transfer.Multipart; package com.nymph.context; /** * 参数解析器将要解析的对象 * @author NYMPH * @date 2017年9月21日下午8:16:00 */ public class ContextParameter { private Map<String, String[]> params; private ContextWrapper context; private Multipart multipart;
private MapperInfo mapperInfo;
NymphWeb/nymph
com/nymph/bean/BeansComponent.java
// Path: com/nymph/interceptor/Interceptors.java // public interface Interceptors extends Comparable<Interceptors> { // /** // * 被拦截的方法之前会执行此方法 // * @param asyncContext 异步Context,可以方法执行之前对request和response进行操作 // * @return <code>true</code>表示放行, <code>false</code>表示拦截 // */ // boolean preHandle(ContextWrapper asyncContext); // /** // * 被拦截的方法之后会执行此方法 // * @param asyncContext 异步Context,可以在方法执行之后对request和response进行操作 // */ // void behindHandle(ContextWrapper asyncContext); // /** // * 当实现多个拦截器, 形成拦截器链时, 重写这个方法可以保证拦截器链的执行顺序 // * 值越小的越会优先执行 // * @return 返回一个代表执行顺序的int值 // */ // int getOrder(); // // default int compareTo(Interceptors o) { // return this.getOrder() - o.getOrder(); // } // }
import com.nymph.interceptor.Interceptors; import java.lang.annotation.Annotation; import java.util.List; import java.util.Optional;
package com.nymph.bean; public interface BeansComponent { /** * 根据注解类型获取组件Bean * @param anno 指定的注解 * @return 对应的bean组件 */ Optional<Object> getComponent(Class<? extends Annotation> anno); /** * 获取拦截器链 * @return */
// Path: com/nymph/interceptor/Interceptors.java // public interface Interceptors extends Comparable<Interceptors> { // /** // * 被拦截的方法之前会执行此方法 // * @param asyncContext 异步Context,可以方法执行之前对request和response进行操作 // * @return <code>true</code>表示放行, <code>false</code>表示拦截 // */ // boolean preHandle(ContextWrapper asyncContext); // /** // * 被拦截的方法之后会执行此方法 // * @param asyncContext 异步Context,可以在方法执行之后对request和response进行操作 // */ // void behindHandle(ContextWrapper asyncContext); // /** // * 当实现多个拦截器, 形成拦截器链时, 重写这个方法可以保证拦截器链的执行顺序 // * 值越小的越会优先执行 // * @return 返回一个代表执行顺序的int值 // */ // int getOrder(); // // default int compareTo(Interceptors o) { // return this.getOrder() - o.getOrder(); // } // } // Path: com/nymph/bean/BeansComponent.java import com.nymph.interceptor.Interceptors; import java.lang.annotation.Annotation; import java.util.List; import java.util.Optional; package com.nymph.bean; public interface BeansComponent { /** * 根据注解类型获取组件Bean * @param anno 指定的注解 * @return 对应的bean组件 */ Optional<Object> getComponent(Class<? extends Annotation> anno); /** * 获取拦截器链 * @return */
List<Interceptors> getInterceptors();
NymphWeb/nymph
com/nymph/context/AsyncDispatcher.java
// Path: com/nymph/queue/NyQueue.java // public class NyQueue<E> extends ConcurrentLinkedQueue<E> { // // private static final long serialVersionUID = 1L; // // private final AtomicInteger size = new AtomicInteger(); // // /** Lock held by take, poll, etc */ // private final ReentrantLock takeLock = new ReentrantLock(); // // /** Wait queue for waiting takes */ // private final Condition notEmpty = takeLock.newCondition(); // // /** Lock held by put, offer, etc */ // private final ReentrantLock putLock = new ReentrantLock(); // // /** Wait queue for waiting puts */ // private final Condition notFull = putLock.newCondition(); // // /** // * 往队列尾部插入元素,容量最大值时等待 // * @return // * @throws InterruptedException // */ // public void put(E e) throws InterruptedException { // int c = -1; // final ReentrantLock putLock = this.putLock; // final AtomicInteger count = this.size; // putLock.lockInterruptibly(); // try { // /* // * Note that count is used in wait guard even though it is // * not protected by lock. This works because count can // * only decrease at this point (all other puts are shut // * out by lock), and we (or some other waiting put) are // * signalled if it ever changes from capacity. Similarly // * for all other uses of count in other wait guards. // */ // while (count.get() == Integer.MAX_VALUE) { // notFull.await(); // } // super.offer(e); // c = count.getAndIncrement(); // if (c + 1 < Integer.MAX_VALUE) // notFull.signal(); // } finally { // putLock.unlock(); // } // if (c == 0) // signalNotEmpty(); // } // /** 当前队列内节点个数 */ // public int size() { // return size.get(); // } // // /** 从队列头部获取元素, size为空时等待 // * @throws InterruptedException */ // public E take() throws InterruptedException { // E x; // int c = -1; // final AtomicInteger count = this.size; // final ReentrantLock takeLock = this.takeLock; // takeLock.lockInterruptibly(); // try { // while (count.get() == 0) { // notEmpty.await(); // } // x = super.poll(); // c = count.getAndDecrement(); // if (c > 1) // notEmpty.signal(); // } finally { // takeLock.unlock(); // } // if (c == Integer.MAX_VALUE) // signalNotFull(); // return x; // } // // /** // * Signals a waiting take. Called only from put/offer (which do not // * otherwise ordinarily lock takeLock.) // */ // private void signalNotEmpty() { // final ReentrantLock takeLock = this.takeLock; // takeLock.lock(); // try { // notEmpty.signal(); // } finally { // takeLock.unlock(); // } // } // // /** // * Signals a waiting put. Called only from take/poll. // */ // private void signalNotFull() { // final ReentrantLock putLock = this.putLock; // putLock.lock(); // try { // notFull.signal(); // } finally { // putLock.unlock(); // } // } // // } // // Path: com/nymph/utils/PoolUtil.java // public abstract class PoolUtil { // // public static ThreadPoolExecutor fixedThreadPool() { // int processors = Runtime.getRuntime().availableProcessors(); // return new ThreadPoolExecutor(processors * 2, processors * 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); // } // // public static ThreadPoolExecutor cacheThreadPool() { // return new ThreadPoolExecutor(0, 200, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); // } // // }
import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nymph.queue.NyQueue; import com.nymph.utils.PoolUtil;
package com.nymph.context; /** * Copyright 2017 author: LiuYang, LiangTianDong * * 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. * * * 请求调度器, 基于生产消费的模型来实现并发的处理请求和响应结果 * @author LiuYang * @author LiangTianDong * @date 2017年9月26日下午8:16:28 */ public final class AsyncDispatcher extends HttpServlet implements Runnable { private static final long serialVersionUID = 1L; // 执行队列的线程池
// Path: com/nymph/queue/NyQueue.java // public class NyQueue<E> extends ConcurrentLinkedQueue<E> { // // private static final long serialVersionUID = 1L; // // private final AtomicInteger size = new AtomicInteger(); // // /** Lock held by take, poll, etc */ // private final ReentrantLock takeLock = new ReentrantLock(); // // /** Wait queue for waiting takes */ // private final Condition notEmpty = takeLock.newCondition(); // // /** Lock held by put, offer, etc */ // private final ReentrantLock putLock = new ReentrantLock(); // // /** Wait queue for waiting puts */ // private final Condition notFull = putLock.newCondition(); // // /** // * 往队列尾部插入元素,容量最大值时等待 // * @return // * @throws InterruptedException // */ // public void put(E e) throws InterruptedException { // int c = -1; // final ReentrantLock putLock = this.putLock; // final AtomicInteger count = this.size; // putLock.lockInterruptibly(); // try { // /* // * Note that count is used in wait guard even though it is // * not protected by lock. This works because count can // * only decrease at this point (all other puts are shut // * out by lock), and we (or some other waiting put) are // * signalled if it ever changes from capacity. Similarly // * for all other uses of count in other wait guards. // */ // while (count.get() == Integer.MAX_VALUE) { // notFull.await(); // } // super.offer(e); // c = count.getAndIncrement(); // if (c + 1 < Integer.MAX_VALUE) // notFull.signal(); // } finally { // putLock.unlock(); // } // if (c == 0) // signalNotEmpty(); // } // /** 当前队列内节点个数 */ // public int size() { // return size.get(); // } // // /** 从队列头部获取元素, size为空时等待 // * @throws InterruptedException */ // public E take() throws InterruptedException { // E x; // int c = -1; // final AtomicInteger count = this.size; // final ReentrantLock takeLock = this.takeLock; // takeLock.lockInterruptibly(); // try { // while (count.get() == 0) { // notEmpty.await(); // } // x = super.poll(); // c = count.getAndDecrement(); // if (c > 1) // notEmpty.signal(); // } finally { // takeLock.unlock(); // } // if (c == Integer.MAX_VALUE) // signalNotFull(); // return x; // } // // /** // * Signals a waiting take. Called only from put/offer (which do not // * otherwise ordinarily lock takeLock.) // */ // private void signalNotEmpty() { // final ReentrantLock takeLock = this.takeLock; // takeLock.lock(); // try { // notEmpty.signal(); // } finally { // takeLock.unlock(); // } // } // // /** // * Signals a waiting put. Called only from take/poll. // */ // private void signalNotFull() { // final ReentrantLock putLock = this.putLock; // putLock.lock(); // try { // notFull.signal(); // } finally { // putLock.unlock(); // } // } // // } // // Path: com/nymph/utils/PoolUtil.java // public abstract class PoolUtil { // // public static ThreadPoolExecutor fixedThreadPool() { // int processors = Runtime.getRuntime().availableProcessors(); // return new ThreadPoolExecutor(processors * 2, processors * 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); // } // // public static ThreadPoolExecutor cacheThreadPool() { // return new ThreadPoolExecutor(0, 200, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); // } // // } // Path: com/nymph/context/AsyncDispatcher.java import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nymph.queue.NyQueue; import com.nymph.utils.PoolUtil; package com.nymph.context; /** * Copyright 2017 author: LiuYang, LiangTianDong * * 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. * * * 请求调度器, 基于生产消费的模型来实现并发的处理请求和响应结果 * @author LiuYang * @author LiangTianDong * @date 2017年9月26日下午8:16:28 */ public final class AsyncDispatcher extends HttpServlet implements Runnable { private static final long serialVersionUID = 1L; // 执行队列的线程池
private final ExecutorService contextPool = PoolUtil.cacheThreadPool();
NymphWeb/nymph
com/nymph/context/AsyncDispatcher.java
// Path: com/nymph/queue/NyQueue.java // public class NyQueue<E> extends ConcurrentLinkedQueue<E> { // // private static final long serialVersionUID = 1L; // // private final AtomicInteger size = new AtomicInteger(); // // /** Lock held by take, poll, etc */ // private final ReentrantLock takeLock = new ReentrantLock(); // // /** Wait queue for waiting takes */ // private final Condition notEmpty = takeLock.newCondition(); // // /** Lock held by put, offer, etc */ // private final ReentrantLock putLock = new ReentrantLock(); // // /** Wait queue for waiting puts */ // private final Condition notFull = putLock.newCondition(); // // /** // * 往队列尾部插入元素,容量最大值时等待 // * @return // * @throws InterruptedException // */ // public void put(E e) throws InterruptedException { // int c = -1; // final ReentrantLock putLock = this.putLock; // final AtomicInteger count = this.size; // putLock.lockInterruptibly(); // try { // /* // * Note that count is used in wait guard even though it is // * not protected by lock. This works because count can // * only decrease at this point (all other puts are shut // * out by lock), and we (or some other waiting put) are // * signalled if it ever changes from capacity. Similarly // * for all other uses of count in other wait guards. // */ // while (count.get() == Integer.MAX_VALUE) { // notFull.await(); // } // super.offer(e); // c = count.getAndIncrement(); // if (c + 1 < Integer.MAX_VALUE) // notFull.signal(); // } finally { // putLock.unlock(); // } // if (c == 0) // signalNotEmpty(); // } // /** 当前队列内节点个数 */ // public int size() { // return size.get(); // } // // /** 从队列头部获取元素, size为空时等待 // * @throws InterruptedException */ // public E take() throws InterruptedException { // E x; // int c = -1; // final AtomicInteger count = this.size; // final ReentrantLock takeLock = this.takeLock; // takeLock.lockInterruptibly(); // try { // while (count.get() == 0) { // notEmpty.await(); // } // x = super.poll(); // c = count.getAndDecrement(); // if (c > 1) // notEmpty.signal(); // } finally { // takeLock.unlock(); // } // if (c == Integer.MAX_VALUE) // signalNotFull(); // return x; // } // // /** // * Signals a waiting take. Called only from put/offer (which do not // * otherwise ordinarily lock takeLock.) // */ // private void signalNotEmpty() { // final ReentrantLock takeLock = this.takeLock; // takeLock.lock(); // try { // notEmpty.signal(); // } finally { // takeLock.unlock(); // } // } // // /** // * Signals a waiting put. Called only from take/poll. // */ // private void signalNotFull() { // final ReentrantLock putLock = this.putLock; // putLock.lock(); // try { // notFull.signal(); // } finally { // putLock.unlock(); // } // } // // } // // Path: com/nymph/utils/PoolUtil.java // public abstract class PoolUtil { // // public static ThreadPoolExecutor fixedThreadPool() { // int processors = Runtime.getRuntime().availableProcessors(); // return new ThreadPoolExecutor(processors * 2, processors * 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); // } // // public static ThreadPoolExecutor cacheThreadPool() { // return new ThreadPoolExecutor(0, 200, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); // } // // }
import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nymph.queue.NyQueue; import com.nymph.utils.PoolUtil;
package com.nymph.context; /** * Copyright 2017 author: LiuYang, LiangTianDong * * 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. * * * 请求调度器, 基于生产消费的模型来实现并发的处理请求和响应结果 * @author LiuYang * @author LiangTianDong * @date 2017年9月26日下午8:16:28 */ public final class AsyncDispatcher extends HttpServlet implements Runnable { private static final long serialVersionUID = 1L; // 执行队列的线程池 private final ExecutorService contextPool = PoolUtil.cacheThreadPool(); private final ExecutorService paramPool = PoolUtil.cacheThreadPool(); private final ExecutorService viewPool = PoolUtil.cacheThreadPool(); // context队列
// Path: com/nymph/queue/NyQueue.java // public class NyQueue<E> extends ConcurrentLinkedQueue<E> { // // private static final long serialVersionUID = 1L; // // private final AtomicInteger size = new AtomicInteger(); // // /** Lock held by take, poll, etc */ // private final ReentrantLock takeLock = new ReentrantLock(); // // /** Wait queue for waiting takes */ // private final Condition notEmpty = takeLock.newCondition(); // // /** Lock held by put, offer, etc */ // private final ReentrantLock putLock = new ReentrantLock(); // // /** Wait queue for waiting puts */ // private final Condition notFull = putLock.newCondition(); // // /** // * 往队列尾部插入元素,容量最大值时等待 // * @return // * @throws InterruptedException // */ // public void put(E e) throws InterruptedException { // int c = -1; // final ReentrantLock putLock = this.putLock; // final AtomicInteger count = this.size; // putLock.lockInterruptibly(); // try { // /* // * Note that count is used in wait guard even though it is // * not protected by lock. This works because count can // * only decrease at this point (all other puts are shut // * out by lock), and we (or some other waiting put) are // * signalled if it ever changes from capacity. Similarly // * for all other uses of count in other wait guards. // */ // while (count.get() == Integer.MAX_VALUE) { // notFull.await(); // } // super.offer(e); // c = count.getAndIncrement(); // if (c + 1 < Integer.MAX_VALUE) // notFull.signal(); // } finally { // putLock.unlock(); // } // if (c == 0) // signalNotEmpty(); // } // /** 当前队列内节点个数 */ // public int size() { // return size.get(); // } // // /** 从队列头部获取元素, size为空时等待 // * @throws InterruptedException */ // public E take() throws InterruptedException { // E x; // int c = -1; // final AtomicInteger count = this.size; // final ReentrantLock takeLock = this.takeLock; // takeLock.lockInterruptibly(); // try { // while (count.get() == 0) { // notEmpty.await(); // } // x = super.poll(); // c = count.getAndDecrement(); // if (c > 1) // notEmpty.signal(); // } finally { // takeLock.unlock(); // } // if (c == Integer.MAX_VALUE) // signalNotFull(); // return x; // } // // /** // * Signals a waiting take. Called only from put/offer (which do not // * otherwise ordinarily lock takeLock.) // */ // private void signalNotEmpty() { // final ReentrantLock takeLock = this.takeLock; // takeLock.lock(); // try { // notEmpty.signal(); // } finally { // takeLock.unlock(); // } // } // // /** // * Signals a waiting put. Called only from take/poll. // */ // private void signalNotFull() { // final ReentrantLock putLock = this.putLock; // putLock.lock(); // try { // notFull.signal(); // } finally { // putLock.unlock(); // } // } // // } // // Path: com/nymph/utils/PoolUtil.java // public abstract class PoolUtil { // // public static ThreadPoolExecutor fixedThreadPool() { // int processors = Runtime.getRuntime().availableProcessors(); // return new ThreadPoolExecutor(processors * 2, processors * 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); // } // // public static ThreadPoolExecutor cacheThreadPool() { // return new ThreadPoolExecutor(0, 200, 60L, TimeUnit.SECONDS, new SynchronousQueue<>()); // } // // } // Path: com/nymph/context/AsyncDispatcher.java import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nymph.queue.NyQueue; import com.nymph.utils.PoolUtil; package com.nymph.context; /** * Copyright 2017 author: LiuYang, LiangTianDong * * 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. * * * 请求调度器, 基于生产消费的模型来实现并发的处理请求和响应结果 * @author LiuYang * @author LiangTianDong * @date 2017年9月26日下午8:16:28 */ public final class AsyncDispatcher extends HttpServlet implements Runnable { private static final long serialVersionUID = 1L; // 执行队列的线程池 private final ExecutorService contextPool = PoolUtil.cacheThreadPool(); private final ExecutorService paramPool = PoolUtil.cacheThreadPool(); private final ExecutorService viewPool = PoolUtil.cacheThreadPool(); // context队列
private final NyQueue<ContextWrapper> contexts = new NyQueue<>();
NymphWeb/nymph
com/nymph/bean/core/PropertyValueInjection.java
// Path: com/nymph/bean/BeansProxy.java // public interface BeansProxy { // /** // * Jdk的动态代理, 可以在此返回代理对象注册到bean工厂 // * @param bean bean的实例 // * @return 代理后的对象 // */ // Object proxyBean(Object bean); // // }
import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.nymph.annotation.Injection; import com.nymph.bean.BeansProxy;
package com.nymph.bean.core; /** * 注入bean中被@Injection注解标识的字段或方法 * @author LiuYang * @author LiangTianDong * @date 2017年10月3日下午2:37:44 */ public class PropertyValueInjection { private static final Logger LOG = LoggerFactory.getLogger(PropertyValueInjection.class); private Map<String, Object> beanContainer; private Map<String, Boolean> signs;
// Path: com/nymph/bean/BeansProxy.java // public interface BeansProxy { // /** // * Jdk的动态代理, 可以在此返回代理对象注册到bean工厂 // * @param bean bean的实例 // * @return 代理后的对象 // */ // Object proxyBean(Object bean); // // } // Path: com/nymph/bean/core/PropertyValueInjection.java import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.nymph.annotation.Injection; import com.nymph.bean.BeansProxy; package com.nymph.bean.core; /** * 注入bean中被@Injection注解标识的字段或方法 * @author LiuYang * @author LiangTianDong * @date 2017年10月3日下午2:37:44 */ public class PropertyValueInjection { private static final Logger LOG = LoggerFactory.getLogger(PropertyValueInjection.class); private Map<String, Object> beanContainer; private Map<String, Boolean> signs;
private BeansProxy proxyHandler;
NymphWeb/nymph
com/nymph/bean/web/MapperInfoContainer.java
// Path: com/nymph/utils/AnnoUtil.java // public abstract class AnnoUtil { // // /** // * 判断一个注解数组是否包含某个注解相同类型的注解... // * @param annos 注解数组 // * @param parent 目标注解 // * @return 注解数组中包含的注解 // */ // public static Annotation get(Annotation[] annos, Class<? extends Annotation> parent) { // for (Annotation annotation : annos) { // if (annotation.annotationType().isAnnotationPresent(parent)) { // return annotation; // } // } // return null; // } // // /** // * 判断一个注解数组是否包含某个注解相同类型的注解... // * @param annos 注解数组 // * @param parent 目标注解 // * @return 注解数组中包含的注解类型 // */ // public static Class<? extends Annotation> getType(Annotation[] annos, Class<? extends Annotation> parent) { // for (Annotation annotation : annos) { // Class<? extends Annotation> annotationType = annotation.annotationType(); // if (annotationType.isAnnotationPresent(parent)) { // return annotationType; // } // } // return null; // } // /** // * 判断一个注解数组中是否包含某个注解 // * @param annos 注解数组 // * @param parent 目标注解 // * @return <code>true</code> <b>or</b> <code>false</code> // */ // public static boolean exist(Annotation[] annos, Class<? extends Annotation> parent) { // for (Annotation annotation : annos) { // if (annotation.annotationType().isAnnotationPresent(parent) || // annotation.annotationType() == parent) { // return true; // } // } // return false; // } // // /** // * 获取注解的指定方法的值 // * @param annotation 目标注解 // * @param methodName 注解的方法名 // * @return 结果 // */ // public static Object invoke(Annotation annotation, String methodName) { // try { // Class<? extends Annotation> annotationType = annotation.annotationType(); // return annotationType.getMethod(methodName).invoke(annotation); // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // /** // * 获取注解的value方法的值 // * @param annotation 目标注解 // * @return 结果 // */ // public static String getValueOfValueMethod(Annotation annotation) { // return String.valueOf(invoke(annotation, "value")); // } // // }
import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.nymph.annotation.HTTP; import com.nymph.annotation.Request; import com.nymph.utils.AnnoUtil;
/** * */ package com.nymph.bean.web; /** * 关于web层的bean的一些处理, 主要是将一个完整的url映射到具体的一个方法, 这样可以加快访问的速度, 直接通过浏览器 * 的url地址的字符串就能获取到对应的类和方法 * @author NYMPH * @date 2017年9月26日2017年9月26日 */ public class MapperInfoContainer { private final Map<String, MapperInfo> httpMap = new HashMap<>(); /** * 对拥有@HTTP注解的bean进行处理主要是将@HTTP注解的value和@Request系列注解(@GET这种) * 的value拼接成一个完整的表示url地址的字符串, 然后存入map中, 这样当一个请求访问过来 * 时只需要拿到这个请求的uri就可以直接获取到对应的Class和Method,如果用@UrlHolder * 注解这种占位符形式的url的话就只有遍历来寻找是否存在请求所映射的类了 * @param clazz 待处理的Class */ public void filterAlsoSave(Class<?> clazz) throws IllegalAccessException { HTTP http = clazz.getAnnotation(HTTP.class); // 没有@HTTP注解的bean则不进行处理 if (http == null) return; for (Method method : clazz.getDeclaredMethods()) { Annotation[] annotations = method.getAnnotations();
// Path: com/nymph/utils/AnnoUtil.java // public abstract class AnnoUtil { // // /** // * 判断一个注解数组是否包含某个注解相同类型的注解... // * @param annos 注解数组 // * @param parent 目标注解 // * @return 注解数组中包含的注解 // */ // public static Annotation get(Annotation[] annos, Class<? extends Annotation> parent) { // for (Annotation annotation : annos) { // if (annotation.annotationType().isAnnotationPresent(parent)) { // return annotation; // } // } // return null; // } // // /** // * 判断一个注解数组是否包含某个注解相同类型的注解... // * @param annos 注解数组 // * @param parent 目标注解 // * @return 注解数组中包含的注解类型 // */ // public static Class<? extends Annotation> getType(Annotation[] annos, Class<? extends Annotation> parent) { // for (Annotation annotation : annos) { // Class<? extends Annotation> annotationType = annotation.annotationType(); // if (annotationType.isAnnotationPresent(parent)) { // return annotationType; // } // } // return null; // } // /** // * 判断一个注解数组中是否包含某个注解 // * @param annos 注解数组 // * @param parent 目标注解 // * @return <code>true</code> <b>or</b> <code>false</code> // */ // public static boolean exist(Annotation[] annos, Class<? extends Annotation> parent) { // for (Annotation annotation : annos) { // if (annotation.annotationType().isAnnotationPresent(parent) || // annotation.annotationType() == parent) { // return true; // } // } // return false; // } // // /** // * 获取注解的指定方法的值 // * @param annotation 目标注解 // * @param methodName 注解的方法名 // * @return 结果 // */ // public static Object invoke(Annotation annotation, String methodName) { // try { // Class<? extends Annotation> annotationType = annotation.annotationType(); // return annotationType.getMethod(methodName).invoke(annotation); // } catch (Exception e) { // e.printStackTrace(); // return null; // } // } // // /** // * 获取注解的value方法的值 // * @param annotation 目标注解 // * @return 结果 // */ // public static String getValueOfValueMethod(Annotation annotation) { // return String.valueOf(invoke(annotation, "value")); // } // // } // Path: com/nymph/bean/web/MapperInfoContainer.java import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.nymph.annotation.HTTP; import com.nymph.annotation.Request; import com.nymph.utils.AnnoUtil; /** * */ package com.nymph.bean.web; /** * 关于web层的bean的一些处理, 主要是将一个完整的url映射到具体的一个方法, 这样可以加快访问的速度, 直接通过浏览器 * 的url地址的字符串就能获取到对应的类和方法 * @author NYMPH * @date 2017年9月26日2017年9月26日 */ public class MapperInfoContainer { private final Map<String, MapperInfo> httpMap = new HashMap<>(); /** * 对拥有@HTTP注解的bean进行处理主要是将@HTTP注解的value和@Request系列注解(@GET这种) * 的value拼接成一个完整的表示url地址的字符串, 然后存入map中, 这样当一个请求访问过来 * 时只需要拿到这个请求的uri就可以直接获取到对应的Class和Method,如果用@UrlHolder * 注解这种占位符形式的url的话就只有遍历来寻找是否存在请求所映射的类了 * @param clazz 待处理的Class */ public void filterAlsoSave(Class<?> clazz) throws IllegalAccessException { HTTP http = clazz.getAnnotation(HTTP.class); // 没有@HTTP注解的bean则不进行处理 if (http == null) return; for (Method method : clazz.getDeclaredMethods()) { Annotation[] annotations = method.getAnnotations();
Annotation request = AnnoUtil.get(annotations, Request.class);
NymphWeb/nymph
com/nymph/json/Jsons.java
// Path: com/nymph/utils/DateUtil.java // public abstract class DateUtil { // // /** // * 将Date解析成指定格式的字符串 // * @param date // * @param format // * @return // */ // public static String resolve(Date date, String format) { // Instant milli = Instant.ofEpochMilli(date.getTime()); // LocalDateTime ofInstant = LocalDateTime.ofInstant(milli, ZoneId.of("Asia/Shanghai")); // DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format); // return ofInstant.format(formatter); // } // /** // * 将指定格式的字符串解析成Date // * @param date // * @param format // * @return // */ // public static Date resolve(String date, String format) { // try { // return new SimpleDateFormat(format).parse(date); // } catch (ParseException e) { // e.printStackTrace(); // } // return new Date(); // } // /** // * 将一个时间格式的字符串解析成Date 只保留年月日 // * @param date // * @return // */ // public static Date onlyDate(String date) { // try { // return new SimpleDateFormat("yyyy-MM-dd").parse(date); // } catch (ParseException e) { // e.printStackTrace(); // } // return new Date(); // } // /** // * 将一个Date解析成字符串 只保留年月日 // * @param date // * @return // */ // public static String onlyDate(Date date) { // Instant milli = Instant.ofEpochMilli(date.getTime()); // LocalDateTime ofInstant = LocalDateTime.ofInstant(milli, ZoneId.of("Asia/Shanghai")); // DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // return ofInstant.format(formatter); // } // /** // * 将一个Date解析成yyyy-MM-dd HH:mm:ss格式的字符串 // * @param date // * @return // */ // public static String dateTime(Date date) { // Instant milli = Instant.ofEpochMilli(date.getTime()); // LocalDateTime ofInstant = LocalDateTime.ofInstant(milli, ZoneId.of("Asia/Shanghai")); // DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // return ofInstant.format(formatter); // } // /** // * 将一个yyyy-MM-dd HH:mm:ss的字符串解析成Date // * @param date // * @return // */ // public static Date dateTime(String date) { // try { // return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date); // } catch (ParseException e) { // e.printStackTrace(); // } // return new Date(); // } // }
import java.io.Serializable; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.util.Collection; import java.util.Date; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import com.nymph.utils.DateUtil;
return null; StringBuilder jsons = new StringBuilder("{"); Field[] fields = json.getClass().getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (Field field : fields) { if (field.isAnnotationPresent(Exclude.class)) continue; String fName = field.getName(); Name name = null; if ((name = field.getAnnotation(Name.class)) != null) { fName = name.value(); } jsons.append(",\"").append(fName).append("\":"); if (null == field.get(json)) { jsons.append("\"null\""); continue; } if (isCommonType(field)) { jsons.append(field.get(json)); } else if (Date.class == field.getType()) { String resolve = null; Date date = (Date) field.get(json); if (dateformat != null) {
// Path: com/nymph/utils/DateUtil.java // public abstract class DateUtil { // // /** // * 将Date解析成指定格式的字符串 // * @param date // * @param format // * @return // */ // public static String resolve(Date date, String format) { // Instant milli = Instant.ofEpochMilli(date.getTime()); // LocalDateTime ofInstant = LocalDateTime.ofInstant(milli, ZoneId.of("Asia/Shanghai")); // DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format); // return ofInstant.format(formatter); // } // /** // * 将指定格式的字符串解析成Date // * @param date // * @param format // * @return // */ // public static Date resolve(String date, String format) { // try { // return new SimpleDateFormat(format).parse(date); // } catch (ParseException e) { // e.printStackTrace(); // } // return new Date(); // } // /** // * 将一个时间格式的字符串解析成Date 只保留年月日 // * @param date // * @return // */ // public static Date onlyDate(String date) { // try { // return new SimpleDateFormat("yyyy-MM-dd").parse(date); // } catch (ParseException e) { // e.printStackTrace(); // } // return new Date(); // } // /** // * 将一个Date解析成字符串 只保留年月日 // * @param date // * @return // */ // public static String onlyDate(Date date) { // Instant milli = Instant.ofEpochMilli(date.getTime()); // LocalDateTime ofInstant = LocalDateTime.ofInstant(milli, ZoneId.of("Asia/Shanghai")); // DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // return ofInstant.format(formatter); // } // /** // * 将一个Date解析成yyyy-MM-dd HH:mm:ss格式的字符串 // * @param date // * @return // */ // public static String dateTime(Date date) { // Instant milli = Instant.ofEpochMilli(date.getTime()); // LocalDateTime ofInstant = LocalDateTime.ofInstant(milli, ZoneId.of("Asia/Shanghai")); // DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // return ofInstant.format(formatter); // } // /** // * 将一个yyyy-MM-dd HH:mm:ss的字符串解析成Date // * @param date // * @return // */ // public static Date dateTime(String date) { // try { // return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date); // } catch (ParseException e) { // e.printStackTrace(); // } // return new Date(); // } // } // Path: com/nymph/json/Jsons.java import java.io.Serializable; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.util.Collection; import java.util.Date; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import com.nymph.utils.DateUtil; return null; StringBuilder jsons = new StringBuilder("{"); Field[] fields = json.getClass().getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (Field field : fields) { if (field.isAnnotationPresent(Exclude.class)) continue; String fName = field.getName(); Name name = null; if ((name = field.getAnnotation(Name.class)) != null) { fName = name.value(); } jsons.append(",\"").append(fName).append("\":"); if (null == field.get(json)) { jsons.append("\"null\""); continue; } if (isCommonType(field)) { jsons.append(field.get(json)); } else if (Date.class == field.getType()) { String resolve = null; Date date = (Date) field.get(json); if (dateformat != null) {
resolve = DateUtil.resolve(date, dateformat);
juankysoriano/rainbow
rainbow-lib/src/main/java/com/juankysoriano/rainbow/core/RainbowTaskScheduler.java
// Path: rainbow-lib/src/main/java/com/juankysoriano/rainbow/utils/schedulers/RainbowScheduler.java // public class RainbowScheduler { // private final ScheduledExecutorService scheduler; // private boolean running; // // RainbowScheduler(ScheduledExecutorService scheduler) { // this.scheduler = scheduler; // } // // public void scheduleNow(Runnable runnable) { // scheduler.schedule(runnable, 0, TimeUnit.MILLISECONDS); // } // // public void scheduleAtRate(Runnable runnable, long delay, TimeUnit timeUnit) { // running = true; // scheduler.scheduleAtFixedRate(runnable, 0, delay, timeUnit); // } // // public boolean isTerminated() { // return !running; // } // // public void shutdown() { // scheduler.shutdownNow(); // running = false; // } // // } // // Path: rainbow-lib/src/main/java/com/juankysoriano/rainbow/utils/schedulers/RainbowSchedulers.java // public abstract class RainbowSchedulers { // public static RainbowScheduler single(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstance(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(1, threadFactory)); // } // // /** // * The stack size for the threads on this scheduler is enough to perform long recursion tasks // **/ // public static RainbowScheduler singleForRecursion(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstanceForRecursion(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(1, threadFactory)); // } // // public static RainbowScheduler multiThreaded(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstance(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() * 2, threadFactory)); // } // // public static RainbowScheduler multiThreaded(String name, Priority priority, int threads) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstance(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(threads, threadFactory)); // } // // /** // * The stack size for the threads on this scheduler is enough to perform long recursion tasks // **/ // public static RainbowScheduler multiThreadedForRecursion(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstanceForRecursion(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() * 2, threadFactory)); // } // // public enum Priority { // MAX(Thread.MAX_PRIORITY), // NORMAL(Thread.NORM_PRIORITY), // MIN(Thread.MIN_PRIORITY); // // private int threadPriority; // // Priority(int threadPriority) { // this.threadPriority = threadPriority; // } // } // }
import com.juankysoriano.rainbow.utils.schedulers.RainbowScheduler; import com.juankysoriano.rainbow.utils.schedulers.RainbowSchedulers; import java.util.concurrent.TimeUnit;
package com.juankysoriano.rainbow.core; class RainbowTaskScheduler { private static final long SECOND = TimeUnit.SECONDS.toNanos(1); private final Rainbow rainbow; private final DrawingTask.Step stepTask; private final DrawingTask.Invalidate invalidateTask; private final DrawingTask.Input inputTask;
// Path: rainbow-lib/src/main/java/com/juankysoriano/rainbow/utils/schedulers/RainbowScheduler.java // public class RainbowScheduler { // private final ScheduledExecutorService scheduler; // private boolean running; // // RainbowScheduler(ScheduledExecutorService scheduler) { // this.scheduler = scheduler; // } // // public void scheduleNow(Runnable runnable) { // scheduler.schedule(runnable, 0, TimeUnit.MILLISECONDS); // } // // public void scheduleAtRate(Runnable runnable, long delay, TimeUnit timeUnit) { // running = true; // scheduler.scheduleAtFixedRate(runnable, 0, delay, timeUnit); // } // // public boolean isTerminated() { // return !running; // } // // public void shutdown() { // scheduler.shutdownNow(); // running = false; // } // // } // // Path: rainbow-lib/src/main/java/com/juankysoriano/rainbow/utils/schedulers/RainbowSchedulers.java // public abstract class RainbowSchedulers { // public static RainbowScheduler single(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstance(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(1, threadFactory)); // } // // /** // * The stack size for the threads on this scheduler is enough to perform long recursion tasks // **/ // public static RainbowScheduler singleForRecursion(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstanceForRecursion(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(1, threadFactory)); // } // // public static RainbowScheduler multiThreaded(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstance(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() * 2, threadFactory)); // } // // public static RainbowScheduler multiThreaded(String name, Priority priority, int threads) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstance(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(threads, threadFactory)); // } // // /** // * The stack size for the threads on this scheduler is enough to perform long recursion tasks // **/ // public static RainbowScheduler multiThreadedForRecursion(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstanceForRecursion(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() * 2, threadFactory)); // } // // public enum Priority { // MAX(Thread.MAX_PRIORITY), // NORMAL(Thread.NORM_PRIORITY), // MIN(Thread.MIN_PRIORITY); // // private int threadPriority; // // Priority(int threadPriority) { // this.threadPriority = threadPriority; // } // } // } // Path: rainbow-lib/src/main/java/com/juankysoriano/rainbow/core/RainbowTaskScheduler.java import com.juankysoriano.rainbow.utils.schedulers.RainbowScheduler; import com.juankysoriano.rainbow.utils.schedulers.RainbowSchedulers; import java.util.concurrent.TimeUnit; package com.juankysoriano.rainbow.core; class RainbowTaskScheduler { private static final long SECOND = TimeUnit.SECONDS.toNanos(1); private final Rainbow rainbow; private final DrawingTask.Step stepTask; private final DrawingTask.Invalidate invalidateTask; private final DrawingTask.Input inputTask;
private RainbowScheduler screenScheduler;
juankysoriano/rainbow
rainbow-lib/src/main/java/com/juankysoriano/rainbow/core/RainbowTaskScheduler.java
// Path: rainbow-lib/src/main/java/com/juankysoriano/rainbow/utils/schedulers/RainbowScheduler.java // public class RainbowScheduler { // private final ScheduledExecutorService scheduler; // private boolean running; // // RainbowScheduler(ScheduledExecutorService scheduler) { // this.scheduler = scheduler; // } // // public void scheduleNow(Runnable runnable) { // scheduler.schedule(runnable, 0, TimeUnit.MILLISECONDS); // } // // public void scheduleAtRate(Runnable runnable, long delay, TimeUnit timeUnit) { // running = true; // scheduler.scheduleAtFixedRate(runnable, 0, delay, timeUnit); // } // // public boolean isTerminated() { // return !running; // } // // public void shutdown() { // scheduler.shutdownNow(); // running = false; // } // // } // // Path: rainbow-lib/src/main/java/com/juankysoriano/rainbow/utils/schedulers/RainbowSchedulers.java // public abstract class RainbowSchedulers { // public static RainbowScheduler single(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstance(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(1, threadFactory)); // } // // /** // * The stack size for the threads on this scheduler is enough to perform long recursion tasks // **/ // public static RainbowScheduler singleForRecursion(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstanceForRecursion(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(1, threadFactory)); // } // // public static RainbowScheduler multiThreaded(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstance(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() * 2, threadFactory)); // } // // public static RainbowScheduler multiThreaded(String name, Priority priority, int threads) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstance(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(threads, threadFactory)); // } // // /** // * The stack size for the threads on this scheduler is enough to perform long recursion tasks // **/ // public static RainbowScheduler multiThreadedForRecursion(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstanceForRecursion(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() * 2, threadFactory)); // } // // public enum Priority { // MAX(Thread.MAX_PRIORITY), // NORMAL(Thread.NORM_PRIORITY), // MIN(Thread.MIN_PRIORITY); // // private int threadPriority; // // Priority(int threadPriority) { // this.threadPriority = threadPriority; // } // } // }
import com.juankysoriano.rainbow.utils.schedulers.RainbowScheduler; import com.juankysoriano.rainbow.utils.schedulers.RainbowSchedulers; import java.util.concurrent.TimeUnit;
@Override public void run() { rainbow.getRainbowDrawer().beginDraw(); rainbow.onDrawingStep(); rainbow.getRainbowDrawer().endDraw(); } }); } void scheduleDrawing(int stepRate, int frameRate, int inputRate) { screenScheduler().scheduleAtRate(stepTask, SECOND / stepRate, TimeUnit.NANOSECONDS); screenScheduler().scheduleAtRate(invalidateTask, SECOND / frameRate, TimeUnit.NANOSECONDS); inputScheduler().scheduleAtRate(inputTask, SECOND / inputRate, TimeUnit.NANOSECONDS); } boolean isTerminated() { return screenScheduler().isTerminated() || inputScheduler().isTerminated(); } void shutdown() { stepTask.shutdown(); invalidateTask.shutdown(); inputTask.shutdown(); screenScheduler().shutdown(); inputScheduler().shutdown(); } private RainbowScheduler screenScheduler() { if (screenScheduler == null || screenScheduler.isTerminated()) {
// Path: rainbow-lib/src/main/java/com/juankysoriano/rainbow/utils/schedulers/RainbowScheduler.java // public class RainbowScheduler { // private final ScheduledExecutorService scheduler; // private boolean running; // // RainbowScheduler(ScheduledExecutorService scheduler) { // this.scheduler = scheduler; // } // // public void scheduleNow(Runnable runnable) { // scheduler.schedule(runnable, 0, TimeUnit.MILLISECONDS); // } // // public void scheduleAtRate(Runnable runnable, long delay, TimeUnit timeUnit) { // running = true; // scheduler.scheduleAtFixedRate(runnable, 0, delay, timeUnit); // } // // public boolean isTerminated() { // return !running; // } // // public void shutdown() { // scheduler.shutdownNow(); // running = false; // } // // } // // Path: rainbow-lib/src/main/java/com/juankysoriano/rainbow/utils/schedulers/RainbowSchedulers.java // public abstract class RainbowSchedulers { // public static RainbowScheduler single(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstance(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(1, threadFactory)); // } // // /** // * The stack size for the threads on this scheduler is enough to perform long recursion tasks // **/ // public static RainbowScheduler singleForRecursion(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstanceForRecursion(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(1, threadFactory)); // } // // public static RainbowScheduler multiThreaded(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstance(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() * 2, threadFactory)); // } // // public static RainbowScheduler multiThreaded(String name, Priority priority, int threads) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstance(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(threads, threadFactory)); // } // // /** // * The stack size for the threads on this scheduler is enough to perform long recursion tasks // **/ // public static RainbowScheduler multiThreadedForRecursion(String name, Priority priority) { // ThreadFactory threadFactory = RainbowThreadFactory.newInstanceForRecursion(name, priority.threadPriority); // return new RainbowScheduler(Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors() * 2, threadFactory)); // } // // public enum Priority { // MAX(Thread.MAX_PRIORITY), // NORMAL(Thread.NORM_PRIORITY), // MIN(Thread.MIN_PRIORITY); // // private int threadPriority; // // Priority(int threadPriority) { // this.threadPriority = threadPriority; // } // } // } // Path: rainbow-lib/src/main/java/com/juankysoriano/rainbow/core/RainbowTaskScheduler.java import com.juankysoriano.rainbow.utils.schedulers.RainbowScheduler; import com.juankysoriano.rainbow.utils.schedulers.RainbowSchedulers; import java.util.concurrent.TimeUnit; @Override public void run() { rainbow.getRainbowDrawer().beginDraw(); rainbow.onDrawingStep(); rainbow.getRainbowDrawer().endDraw(); } }); } void scheduleDrawing(int stepRate, int frameRate, int inputRate) { screenScheduler().scheduleAtRate(stepTask, SECOND / stepRate, TimeUnit.NANOSECONDS); screenScheduler().scheduleAtRate(invalidateTask, SECOND / frameRate, TimeUnit.NANOSECONDS); inputScheduler().scheduleAtRate(inputTask, SECOND / inputRate, TimeUnit.NANOSECONDS); } boolean isTerminated() { return screenScheduler().isTerminated() || inputScheduler().isTerminated(); } void shutdown() { stepTask.shutdown(); invalidateTask.shutdown(); inputTask.shutdown(); screenScheduler().shutdown(); inputScheduler().shutdown(); } private RainbowScheduler screenScheduler() { if (screenScheduler == null || screenScheduler.isTerminated()) {
screenScheduler = RainbowSchedulers.single("Drawing", RainbowSchedulers.Priority.MAX);
simondlevy/BreezySLAM
java/edu/wlu/cs/levy/breezyslam/robots/WheeledRobot.java
// Path: java/edu/wlu/cs/levy/breezyslam/components/PoseChange.java // public class PoseChange // { // // /** // * Creates a new PoseChange object with specified velocities. // */ // public PoseChange(double dxy_mm, double dtheta_degrees, double dtSeconds) // { // this.dxy_mm = dxy_mm; // this.dtheta_degrees = dtheta_degrees; // this.dt_seconds = dtSeconds; // } // // /** // * Creates a new PoseChange object with zero velocities. // */ // public PoseChange() // { // this.dxy_mm = 0; // this.dtheta_degrees = 0; // this.dt_seconds = 0; // } // // /** // * Updates this PoseChange object. // * @param dxy_mm new forward distance traveled in millimeters // * @param dtheta_degrees new angular rotation in degrees // * @param dtSeconds time in seconds since last velocities // */ // public void update(double dxy_mm, double dtheta_degrees, double dtSeconds) // { // double velocity_factor = (dtSeconds > 0) ? (1 / dtSeconds) : 0; // // this.dxy_mm = dxy_mm * velocity_factor; // // this.dtheta_degrees = dtheta_degrees * velocity_factor; // } // // /** // * Returns a string representation of this PoseChange object. // */ // public String toString() // { // return String.format("<dxy=%7.0f mm dtheta = %+3.3f degrees dt = %f s", // this.dxy_mm, this.dtheta_degrees, this.dt_seconds); // } // // /** // * Returns the forward component of this PoseChange object. // */ // public double getDxyMm() // { // return this.dxy_mm; // } // // /** // * Returns the angular component of this PoseChange object. // */ // public double getDthetaDegrees() // { // return this.dtheta_degrees; // } // // /** // * Returns the time component of this PoseChange object. // */ // public double getDtSeconds() // { // return this.dt_seconds; // } // // /** // * Forward component of velocity, in mm to be divided by time in seconds. // */ // protected double dxy_mm; // // /** // * Angular component of velocity, in mm to be divided by time in seconds. // */ // // protected double dtheta_degrees; // // /** // * Time in seconds between successive velocity measurements. // */ // protected double dt_seconds; // }
import edu.wlu.cs.levy.breezyslam.components.PoseChange;
/** * * BreezySLAM: Simple, efficient SLAM in Java * * WheeledRobot.java - Java class for wheeled robots * * Copyright (C) 2014 Simon D. Levy * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This code 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 Lesser General Public License * along with this code. If not, see <http://www.gnu.org/licenses/>. */ package edu.wlu.cs.levy.breezyslam.robots; /** * An abstract class for wheeled robots. Supports computation of forward and angular * poseChange based on odometry. Your subclass should should implement the * extractOdometry method. */ public abstract class WheeledRobot { /** * Builds a WheeledRobot object. Parameters should be based on the specifications for * your robot. * @param wheel_radius_mm radius of each odometry wheel, in meters * @param half_axle_length_mm half the length of the axle between the odometry wheels, in meters * @return a new WheeledRobot object */ protected WheeledRobot(double wheel_radius_mm, double half_axle_length_mm) { this.wheel_radius_mm = wheel_radius_mm; this.half_axle_length_mm = half_axle_length_mm; this.timestamp_seconds_prev = 0; this.left_wheel_degrees_prev = 0; this.right_wheel_degrees_prev = 0; } public String toString() { return String.format("<Wheel radius=%f m Half axle Length=%f m | %s>", this.wheel_radius_mm, this.half_axle_length_mm, this.descriptorString()); } /** * Computes forward and angular poseChange based on odometry. * @param timestamp time stamp, in whatever units your robot uses * @param left_wheel_odometry odometry for left wheel, in whatever units your robot uses * @param right_wheel_odometry odometry for right wheel, in whatever units your robot uses * @return poseChange object representing poseChange for these odometry values */
// Path: java/edu/wlu/cs/levy/breezyslam/components/PoseChange.java // public class PoseChange // { // // /** // * Creates a new PoseChange object with specified velocities. // */ // public PoseChange(double dxy_mm, double dtheta_degrees, double dtSeconds) // { // this.dxy_mm = dxy_mm; // this.dtheta_degrees = dtheta_degrees; // this.dt_seconds = dtSeconds; // } // // /** // * Creates a new PoseChange object with zero velocities. // */ // public PoseChange() // { // this.dxy_mm = 0; // this.dtheta_degrees = 0; // this.dt_seconds = 0; // } // // /** // * Updates this PoseChange object. // * @param dxy_mm new forward distance traveled in millimeters // * @param dtheta_degrees new angular rotation in degrees // * @param dtSeconds time in seconds since last velocities // */ // public void update(double dxy_mm, double dtheta_degrees, double dtSeconds) // { // double velocity_factor = (dtSeconds > 0) ? (1 / dtSeconds) : 0; // // this.dxy_mm = dxy_mm * velocity_factor; // // this.dtheta_degrees = dtheta_degrees * velocity_factor; // } // // /** // * Returns a string representation of this PoseChange object. // */ // public String toString() // { // return String.format("<dxy=%7.0f mm dtheta = %+3.3f degrees dt = %f s", // this.dxy_mm, this.dtheta_degrees, this.dt_seconds); // } // // /** // * Returns the forward component of this PoseChange object. // */ // public double getDxyMm() // { // return this.dxy_mm; // } // // /** // * Returns the angular component of this PoseChange object. // */ // public double getDthetaDegrees() // { // return this.dtheta_degrees; // } // // /** // * Returns the time component of this PoseChange object. // */ // public double getDtSeconds() // { // return this.dt_seconds; // } // // /** // * Forward component of velocity, in mm to be divided by time in seconds. // */ // protected double dxy_mm; // // /** // * Angular component of velocity, in mm to be divided by time in seconds. // */ // // protected double dtheta_degrees; // // /** // * Time in seconds between successive velocity measurements. // */ // protected double dt_seconds; // } // Path: java/edu/wlu/cs/levy/breezyslam/robots/WheeledRobot.java import edu.wlu.cs.levy.breezyslam.components.PoseChange; /** * * BreezySLAM: Simple, efficient SLAM in Java * * WheeledRobot.java - Java class for wheeled robots * * Copyright (C) 2014 Simon D. Levy * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This code 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 Lesser General Public License * along with this code. If not, see <http://www.gnu.org/licenses/>. */ package edu.wlu.cs.levy.breezyslam.robots; /** * An abstract class for wheeled robots. Supports computation of forward and angular * poseChange based on odometry. Your subclass should should implement the * extractOdometry method. */ public abstract class WheeledRobot { /** * Builds a WheeledRobot object. Parameters should be based on the specifications for * your robot. * @param wheel_radius_mm radius of each odometry wheel, in meters * @param half_axle_length_mm half the length of the axle between the odometry wheels, in meters * @return a new WheeledRobot object */ protected WheeledRobot(double wheel_radius_mm, double half_axle_length_mm) { this.wheel_radius_mm = wheel_radius_mm; this.half_axle_length_mm = half_axle_length_mm; this.timestamp_seconds_prev = 0; this.left_wheel_degrees_prev = 0; this.right_wheel_degrees_prev = 0; } public String toString() { return String.format("<Wheel radius=%f m Half axle Length=%f m | %s>", this.wheel_radius_mm, this.half_axle_length_mm, this.descriptorString()); } /** * Computes forward and angular poseChange based on odometry. * @param timestamp time stamp, in whatever units your robot uses * @param left_wheel_odometry odometry for left wheel, in whatever units your robot uses * @param right_wheel_odometry odometry for right wheel, in whatever units your robot uses * @return poseChange object representing poseChange for these odometry values */
public PoseChange computePoseChange( double timestamp, double left_wheel_odometry, double right_wheel_odometry)
NyaaCat/NyaaCore
src/main/java/cat/nyaa/nyaacore/utils/OfflinePlayerUtils.java
// Path: src/main/java/cat/nyaa/nyaacore/NyaaCoreLoader.java // public class NyaaCoreLoader extends JavaPlugin { // private static NyaaCoreLoader instance; // // static { // ConfigurationSerialization.registerClass(NbtItemStack.class); // } // // public NyaaCoreLoader() { // super(); // } // // protected NyaaCoreLoader(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { // super(loader, description, dataFolder, file); // } // // public static NyaaCoreLoader getInstance() { // return instance; // } // // @Override // public void onLoad() { // instance = this; // } // // @Override // public void onEnable() { // Bukkit.getPluginManager().registerEvents(new ClickSelectionUtils._Listener(), this); // Bukkit.getPluginManager().registerEvents(new OfflinePlayerUtils._Listener(), this); // OfflinePlayerUtils.init(); // } // }
import cat.nyaa.nyaacore.NyaaCoreLoader; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableBiMap; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentMap; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.logging.Level; import java.util.stream.Collectors;
Collectors.toConcurrentMap(e -> e.getValue().getUniqueId(), Map.Entry::getKey)); } public static OfflinePlayer lookupPlayer(String name) { OfflinePlayer player = Bukkit.getPlayerExact(name); if (player != null) return player; return playerCache.get(name.toLowerCase(Locale.ENGLISH)); } public static CompletableFuture<BiMap<String, UUID>> lookupPlayerNamesOnline(String... names) { List<String> nameList = new LinkedList<>(Arrays.asList(names)); BiMap<String, UUID> ret = HashBiMap.create(); Iterator<String> iterator = nameList.iterator(); while (iterator.hasNext()) { String n = iterator.next(); OfflinePlayer player = playerCache.get(n.toLowerCase(Locale.ENGLISH)); if (player != null) { iterator.remove(); ret.put(n, player.getUniqueId()); } } HttpClient client = HttpClient.newHttpClient(); HttpRequest req = HttpRequest.newBuilder() .uri(URI.create("https://api.mojang.com/profiles/minecraft")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(new Gson().toJson(List.of(names)))) .build(); return client.sendAsync(req, HttpResponse.BodyHandlers.ofString()) .thenApply((response) -> {
// Path: src/main/java/cat/nyaa/nyaacore/NyaaCoreLoader.java // public class NyaaCoreLoader extends JavaPlugin { // private static NyaaCoreLoader instance; // // static { // ConfigurationSerialization.registerClass(NbtItemStack.class); // } // // public NyaaCoreLoader() { // super(); // } // // protected NyaaCoreLoader(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { // super(loader, description, dataFolder, file); // } // // public static NyaaCoreLoader getInstance() { // return instance; // } // // @Override // public void onLoad() { // instance = this; // } // // @Override // public void onEnable() { // Bukkit.getPluginManager().registerEvents(new ClickSelectionUtils._Listener(), this); // Bukkit.getPluginManager().registerEvents(new OfflinePlayerUtils._Listener(), this); // OfflinePlayerUtils.init(); // } // } // Path: src/main/java/cat/nyaa/nyaacore/utils/OfflinePlayerUtils.java import cat.nyaa.nyaacore.NyaaCoreLoader; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableBiMap; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentMap; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.logging.Level; import java.util.stream.Collectors; Collectors.toConcurrentMap(e -> e.getValue().getUniqueId(), Map.Entry::getKey)); } public static OfflinePlayer lookupPlayer(String name) { OfflinePlayer player = Bukkit.getPlayerExact(name); if (player != null) return player; return playerCache.get(name.toLowerCase(Locale.ENGLISH)); } public static CompletableFuture<BiMap<String, UUID>> lookupPlayerNamesOnline(String... names) { List<String> nameList = new LinkedList<>(Arrays.asList(names)); BiMap<String, UUID> ret = HashBiMap.create(); Iterator<String> iterator = nameList.iterator(); while (iterator.hasNext()) { String n = iterator.next(); OfflinePlayer player = playerCache.get(n.toLowerCase(Locale.ENGLISH)); if (player != null) { iterator.remove(); ret.put(n, player.getUniqueId()); } } HttpClient client = HttpClient.newHttpClient(); HttpRequest req = HttpRequest.newBuilder() .uri(URI.create("https://api.mojang.com/profiles/minecraft")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(new Gson().toJson(List.of(names)))) .build(); return client.sendAsync(req, HttpResponse.BodyHandlers.ofString()) .thenApply((response) -> {
NyaaCoreLoader.getInstance().getLogger().log(Level.FINER,
NyaaCat/NyaaCore
src/main/java/cat/nyaa/nyaacore/utils/SpigotMappingUtils.java
// Path: src/main/java/cat/nyaa/nyaacore/NyaaCoreLoader.java // public class NyaaCoreLoader extends JavaPlugin { // private static NyaaCoreLoader instance; // // static { // ConfigurationSerialization.registerClass(NbtItemStack.class); // } // // public NyaaCoreLoader() { // super(); // } // // protected NyaaCoreLoader(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { // super(loader, description, dataFolder, file); // } // // public static NyaaCoreLoader getInstance() { // return instance; // } // // @Override // public void onLoad() { // instance = this; // } // // @Override // public void onEnable() { // Bukkit.getPluginManager().registerEvents(new ClickSelectionUtils._Listener(), this); // Bukkit.getPluginManager().registerEvents(new OfflinePlayerUtils._Listener(), this); // OfflinePlayerUtils.init(); // } // } // // Path: src/main/java/cat/nyaa/nyaacore/Pair.java // public class Pair<K, V> implements Map.Entry<K, V> { // // private K key; // private V value; // // public Pair(K key, V value) { // this.key = key; // this.value = value; // } // // public Pair(Map.Entry<? extends K, ? extends V> entry) { // this.key = entry.getKey(); // this.value = entry.getValue(); // } // // public static <Ks, Vs> Pair<Ks, Vs> of(Ks key, Vs value) { // return new Pair<>(key, value); // } // // @Override // public K getKey() { // return key; // } // // public K setKey(K key) { // K oldKey = this.key; // this.key = key; // return oldKey; // } // // @Override // public V getValue() { // return value; // } // // @Override // public V setValue(V value) { // V oldValue = this.value; // this.value = value; // return oldValue; // } // // @Override // public int hashCode() { // return (key == null ? 0 : key.hashCode()) * 17 + (value == null ? 0 : value.hashCode()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o instanceof Pair pair) { // return Objects.equals(key, pair.getKey()) && Objects.equals(value, pair.getValue()); // } // return false; // } // // @Override // public String toString() { // return key + "=" + value; // } // }
import cat.nyaa.nyaacore.NyaaCoreLoader; import cat.nyaa.nyaacore.Pair; import org.cadixdev.bombe.type.FieldType; import org.cadixdev.bombe.type.signature.FieldSignature; import org.cadixdev.lorenz.MappingSet; import org.cadixdev.lorenz.io.srg.csrg.CSrgReader; import org.cadixdev.lorenz.model.ClassMapping; import org.cadixdev.lorenz.model.FieldMapping; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Optional;
package cat.nyaa.nyaacore.utils; public class SpigotMappingUtils { static String FILE_NAME = "spigot-deobf.csrg"; @Nullable static MappingSet deobfMappingSet;//DEOBF (obf->deobf) @Nullable static MappingSet obfMappingSet; //obf (deobf->obf) public static void load() throws RuntimeException { InputStream inputStream;
// Path: src/main/java/cat/nyaa/nyaacore/NyaaCoreLoader.java // public class NyaaCoreLoader extends JavaPlugin { // private static NyaaCoreLoader instance; // // static { // ConfigurationSerialization.registerClass(NbtItemStack.class); // } // // public NyaaCoreLoader() { // super(); // } // // protected NyaaCoreLoader(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { // super(loader, description, dataFolder, file); // } // // public static NyaaCoreLoader getInstance() { // return instance; // } // // @Override // public void onLoad() { // instance = this; // } // // @Override // public void onEnable() { // Bukkit.getPluginManager().registerEvents(new ClickSelectionUtils._Listener(), this); // Bukkit.getPluginManager().registerEvents(new OfflinePlayerUtils._Listener(), this); // OfflinePlayerUtils.init(); // } // } // // Path: src/main/java/cat/nyaa/nyaacore/Pair.java // public class Pair<K, V> implements Map.Entry<K, V> { // // private K key; // private V value; // // public Pair(K key, V value) { // this.key = key; // this.value = value; // } // // public Pair(Map.Entry<? extends K, ? extends V> entry) { // this.key = entry.getKey(); // this.value = entry.getValue(); // } // // public static <Ks, Vs> Pair<Ks, Vs> of(Ks key, Vs value) { // return new Pair<>(key, value); // } // // @Override // public K getKey() { // return key; // } // // public K setKey(K key) { // K oldKey = this.key; // this.key = key; // return oldKey; // } // // @Override // public V getValue() { // return value; // } // // @Override // public V setValue(V value) { // V oldValue = this.value; // this.value = value; // return oldValue; // } // // @Override // public int hashCode() { // return (key == null ? 0 : key.hashCode()) * 17 + (value == null ? 0 : value.hashCode()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o instanceof Pair pair) { // return Objects.equals(key, pair.getKey()) && Objects.equals(value, pair.getValue()); // } // return false; // } // // @Override // public String toString() { // return key + "=" + value; // } // } // Path: src/main/java/cat/nyaa/nyaacore/utils/SpigotMappingUtils.java import cat.nyaa.nyaacore.NyaaCoreLoader; import cat.nyaa.nyaacore.Pair; import org.cadixdev.bombe.type.FieldType; import org.cadixdev.bombe.type.signature.FieldSignature; import org.cadixdev.lorenz.MappingSet; import org.cadixdev.lorenz.io.srg.csrg.CSrgReader; import org.cadixdev.lorenz.model.ClassMapping; import org.cadixdev.lorenz.model.FieldMapping; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Optional; package cat.nyaa.nyaacore.utils; public class SpigotMappingUtils { static String FILE_NAME = "spigot-deobf.csrg"; @Nullable static MappingSet deobfMappingSet;//DEOBF (obf->deobf) @Nullable static MappingSet obfMappingSet; //obf (deobf->obf) public static void load() throws RuntimeException { InputStream inputStream;
URL resourceUrl = NyaaCoreLoader.class.getClassLoader().getResource(FILE_NAME);
NyaaCat/NyaaCore
src/main/java/cat/nyaa/nyaacore/utils/SpigotMappingUtils.java
// Path: src/main/java/cat/nyaa/nyaacore/NyaaCoreLoader.java // public class NyaaCoreLoader extends JavaPlugin { // private static NyaaCoreLoader instance; // // static { // ConfigurationSerialization.registerClass(NbtItemStack.class); // } // // public NyaaCoreLoader() { // super(); // } // // protected NyaaCoreLoader(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { // super(loader, description, dataFolder, file); // } // // public static NyaaCoreLoader getInstance() { // return instance; // } // // @Override // public void onLoad() { // instance = this; // } // // @Override // public void onEnable() { // Bukkit.getPluginManager().registerEvents(new ClickSelectionUtils._Listener(), this); // Bukkit.getPluginManager().registerEvents(new OfflinePlayerUtils._Listener(), this); // OfflinePlayerUtils.init(); // } // } // // Path: src/main/java/cat/nyaa/nyaacore/Pair.java // public class Pair<K, V> implements Map.Entry<K, V> { // // private K key; // private V value; // // public Pair(K key, V value) { // this.key = key; // this.value = value; // } // // public Pair(Map.Entry<? extends K, ? extends V> entry) { // this.key = entry.getKey(); // this.value = entry.getValue(); // } // // public static <Ks, Vs> Pair<Ks, Vs> of(Ks key, Vs value) { // return new Pair<>(key, value); // } // // @Override // public K getKey() { // return key; // } // // public K setKey(K key) { // K oldKey = this.key; // this.key = key; // return oldKey; // } // // @Override // public V getValue() { // return value; // } // // @Override // public V setValue(V value) { // V oldValue = this.value; // this.value = value; // return oldValue; // } // // @Override // public int hashCode() { // return (key == null ? 0 : key.hashCode()) * 17 + (value == null ? 0 : value.hashCode()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o instanceof Pair pair) { // return Objects.equals(key, pair.getKey()) && Objects.equals(value, pair.getValue()); // } // return false; // } // // @Override // public String toString() { // return key + "=" + value; // } // }
import cat.nyaa.nyaacore.NyaaCoreLoader; import cat.nyaa.nyaacore.Pair; import org.cadixdev.bombe.type.FieldType; import org.cadixdev.bombe.type.signature.FieldSignature; import org.cadixdev.lorenz.MappingSet; import org.cadixdev.lorenz.io.srg.csrg.CSrgReader; import org.cadixdev.lorenz.model.ClassMapping; import org.cadixdev.lorenz.model.FieldMapping; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Optional;
} public static void checkAndLoad() { if (deobfMappingSet == null || obfMappingSet == null) load(); } public static MappingSet getObfMappingSet() { checkAndLoad(); if (obfMappingSet == null) { throw new RuntimeException("obfMappingSet has not been loaded"); } return obfMappingSet; } public static MappingSet getDeobfMappingSet() { checkAndLoad(); if (deobfMappingSet == null) { throw new RuntimeException("deobfMappingSet has not been loaded"); } return deobfMappingSet; } public static Optional<? extends ClassMapping<?, ?>> getObfuscatedClassMapping(String deobfuscatedClassName) { return getObfMappingSet().getClassMapping(deobfuscatedClassName); } public static Optional<String> getSimpleObfuscatedFieldNameOptional(String deobfuscatedClassName, String fieldName, @Nullable FieldType fieldType) { return getObfuscatedClassAndFieldMapping(deobfuscatedClassName, fieldName, fieldType).map(fieldMappingPair -> fieldMappingPair.getValue().getSimpleDeobfuscatedName()); }
// Path: src/main/java/cat/nyaa/nyaacore/NyaaCoreLoader.java // public class NyaaCoreLoader extends JavaPlugin { // private static NyaaCoreLoader instance; // // static { // ConfigurationSerialization.registerClass(NbtItemStack.class); // } // // public NyaaCoreLoader() { // super(); // } // // protected NyaaCoreLoader(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { // super(loader, description, dataFolder, file); // } // // public static NyaaCoreLoader getInstance() { // return instance; // } // // @Override // public void onLoad() { // instance = this; // } // // @Override // public void onEnable() { // Bukkit.getPluginManager().registerEvents(new ClickSelectionUtils._Listener(), this); // Bukkit.getPluginManager().registerEvents(new OfflinePlayerUtils._Listener(), this); // OfflinePlayerUtils.init(); // } // } // // Path: src/main/java/cat/nyaa/nyaacore/Pair.java // public class Pair<K, V> implements Map.Entry<K, V> { // // private K key; // private V value; // // public Pair(K key, V value) { // this.key = key; // this.value = value; // } // // public Pair(Map.Entry<? extends K, ? extends V> entry) { // this.key = entry.getKey(); // this.value = entry.getValue(); // } // // public static <Ks, Vs> Pair<Ks, Vs> of(Ks key, Vs value) { // return new Pair<>(key, value); // } // // @Override // public K getKey() { // return key; // } // // public K setKey(K key) { // K oldKey = this.key; // this.key = key; // return oldKey; // } // // @Override // public V getValue() { // return value; // } // // @Override // public V setValue(V value) { // V oldValue = this.value; // this.value = value; // return oldValue; // } // // @Override // public int hashCode() { // return (key == null ? 0 : key.hashCode()) * 17 + (value == null ? 0 : value.hashCode()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o instanceof Pair pair) { // return Objects.equals(key, pair.getKey()) && Objects.equals(value, pair.getValue()); // } // return false; // } // // @Override // public String toString() { // return key + "=" + value; // } // } // Path: src/main/java/cat/nyaa/nyaacore/utils/SpigotMappingUtils.java import cat.nyaa.nyaacore.NyaaCoreLoader; import cat.nyaa.nyaacore.Pair; import org.cadixdev.bombe.type.FieldType; import org.cadixdev.bombe.type.signature.FieldSignature; import org.cadixdev.lorenz.MappingSet; import org.cadixdev.lorenz.io.srg.csrg.CSrgReader; import org.cadixdev.lorenz.model.ClassMapping; import org.cadixdev.lorenz.model.FieldMapping; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Optional; } public static void checkAndLoad() { if (deobfMappingSet == null || obfMappingSet == null) load(); } public static MappingSet getObfMappingSet() { checkAndLoad(); if (obfMappingSet == null) { throw new RuntimeException("obfMappingSet has not been loaded"); } return obfMappingSet; } public static MappingSet getDeobfMappingSet() { checkAndLoad(); if (deobfMappingSet == null) { throw new RuntimeException("deobfMappingSet has not been loaded"); } return deobfMappingSet; } public static Optional<? extends ClassMapping<?, ?>> getObfuscatedClassMapping(String deobfuscatedClassName) { return getObfMappingSet().getClassMapping(deobfuscatedClassName); } public static Optional<String> getSimpleObfuscatedFieldNameOptional(String deobfuscatedClassName, String fieldName, @Nullable FieldType fieldType) { return getObfuscatedClassAndFieldMapping(deobfuscatedClassName, fieldName, fieldType).map(fieldMappingPair -> fieldMappingPair.getValue().getSimpleDeobfuscatedName()); }
private static Optional<Pair<? extends ClassMapping<?, ?>, FieldMapping>> getObfuscatedClassAndFieldMapping(String deobfuscatedClassName, String fieldName, @Nullable FieldType fieldType) {
NyaaCat/NyaaCore
src/main/java/cat/nyaa/nyaacore/utils/ClassPathUtils.java
// Path: src/main/java/cat/nyaa/nyaacore/NyaaCoreLoader.java // public class NyaaCoreLoader extends JavaPlugin { // private static NyaaCoreLoader instance; // // static { // ConfigurationSerialization.registerClass(NbtItemStack.class); // } // // public NyaaCoreLoader() { // super(); // } // // protected NyaaCoreLoader(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { // super(loader, description, dataFolder, file); // } // // public static NyaaCoreLoader getInstance() { // return instance; // } // // @Override // public void onLoad() { // instance = this; // } // // @Override // public void onEnable() { // Bukkit.getPluginManager().registerEvents(new ClickSelectionUtils._Listener(), this); // Bukkit.getPluginManager().registerEvents(new OfflinePlayerUtils._Listener(), this); // OfflinePlayerUtils.init(); // } // }
import cat.nyaa.nyaacore.NyaaCoreLoader; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Splitter; import com.google.common.collect.*; import com.google.common.reflect.Reflection; import org.bukkit.plugin.Plugin; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH; import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR; import static java.util.logging.Level.WARNING;
private static Stream<? extends Class<?>> loadClassesInPackage(String pack, Set<ClassInfo> classInfos) { return classInfos .stream() .filter(c -> pack == null || c.getPackageName().startsWith(pack)) .map(ClassInfo::load); } /** * Returns a {@code ClassPathUtils} representing all classes and resources loadable from {@code * classloader} and its ancestor class loaders. * * <p><b>Warning:</b> {@code ClassPathUtils} can find classes and resources only from: * * <ul> * <li>{@link URLClassLoader} instances' {@code file:} URLs * <li>the {@linkplain ClassLoader#getSystemClassLoader() system class loader}. To search the * system class loader even when it is not a {@link URLClassLoader} (as in Java 9), {@code * ClassPathUtils} searches the files from the {@code java.class.path} system property. * </ul> * * @throws IOException if the attempt to read class path resources (jar files or directories) * failed. */ public static ClassPathUtils from(File file, ClassLoader classloader) throws IOException { DefaultScanner scanner = new DefaultScanner(); scanner.scan(file, classloader); return new ClassPathUtils(scanner.getResources()); } private static Logger getLogger() {
// Path: src/main/java/cat/nyaa/nyaacore/NyaaCoreLoader.java // public class NyaaCoreLoader extends JavaPlugin { // private static NyaaCoreLoader instance; // // static { // ConfigurationSerialization.registerClass(NbtItemStack.class); // } // // public NyaaCoreLoader() { // super(); // } // // protected NyaaCoreLoader(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { // super(loader, description, dataFolder, file); // } // // public static NyaaCoreLoader getInstance() { // return instance; // } // // @Override // public void onLoad() { // instance = this; // } // // @Override // public void onEnable() { // Bukkit.getPluginManager().registerEvents(new ClickSelectionUtils._Listener(), this); // Bukkit.getPluginManager().registerEvents(new OfflinePlayerUtils._Listener(), this); // OfflinePlayerUtils.init(); // } // } // Path: src/main/java/cat/nyaa/nyaacore/utils/ClassPathUtils.java import cat.nyaa.nyaacore.NyaaCoreLoader; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Splitter; import com.google.common.collect.*; import com.google.common.reflect.Reflection; import org.bukkit.plugin.Plugin; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH; import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR; import static java.util.logging.Level.WARNING; private static Stream<? extends Class<?>> loadClassesInPackage(String pack, Set<ClassInfo> classInfos) { return classInfos .stream() .filter(c -> pack == null || c.getPackageName().startsWith(pack)) .map(ClassInfo::load); } /** * Returns a {@code ClassPathUtils} representing all classes and resources loadable from {@code * classloader} and its ancestor class loaders. * * <p><b>Warning:</b> {@code ClassPathUtils} can find classes and resources only from: * * <ul> * <li>{@link URLClassLoader} instances' {@code file:} URLs * <li>the {@linkplain ClassLoader#getSystemClassLoader() system class loader}. To search the * system class loader even when it is not a {@link URLClassLoader} (as in Java 9), {@code * ClassPathUtils} searches the files from the {@code java.class.path} system property. * </ul> * * @throws IOException if the attempt to read class path resources (jar files or directories) * failed. */ public static ClassPathUtils from(File file, ClassLoader classloader) throws IOException { DefaultScanner scanner = new DefaultScanner(); scanner.scan(file, classloader); return new ClassPathUtils(scanner.getResources()); } private static Logger getLogger() {
return NyaaCoreLoader.getInstance().getLogger();
NyaaCat/NyaaCore
src/main/java/cat/nyaa/nyaacore/configuration/Setter.java
// Path: src/main/java/cat/nyaa/nyaacore/configuration/Getter.java // static <T, E> T getAccessor(E p, Class<? extends T> cls) { // try { // return cls.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { // throw new RuntimeException(e); // } catch (NoSuchMethodException e) { // try { // return cls.getDeclaredConstructor(cls.getEnclosingClass()).newInstance(p); // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { // throw new RuntimeException(ex); // } // } // }
import java.util.Optional; import static cat.nyaa.nyaacore.configuration.Getter.getAccessor;
package cat.nyaa.nyaacore.configuration; public interface Setter<T> { static <T extends ISerializable> Setter<T> from(T p, Class<? extends Setter<T>> cls) {
// Path: src/main/java/cat/nyaa/nyaacore/configuration/Getter.java // static <T, E> T getAccessor(E p, Class<? extends T> cls) { // try { // return cls.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { // throw new RuntimeException(e); // } catch (NoSuchMethodException e) { // try { // return cls.getDeclaredConstructor(cls.getEnclosingClass()).newInstance(p); // } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { // throw new RuntimeException(ex); // } // } // } // Path: src/main/java/cat/nyaa/nyaacore/configuration/Setter.java import java.util.Optional; import static cat.nyaa.nyaacore.configuration.Getter.getAccessor; package cat.nyaa.nyaacore.configuration; public interface Setter<T> { static <T extends ISerializable> Setter<T> from(T p, Class<? extends Setter<T>> cls) {
return getAccessor(p, cls);
NyaaCat/NyaaCore
src/main/java/cat/nyaa/nyaacore/configuration/ISerializable.java
// Path: src/main/java/cat/nyaa/nyaacore/utils/ReflectionUtils.java // public final class ReflectionUtils { // // /* // * Cache of NMS classes that we've searched for // */ // private static final Map<String, Class<?>> loadedNMSClasses = new HashMap<>(); // /* // * Cache of OBS classes that we've searched for // */ // private static final Map<String, Class<?>> loadedOBCClasses = new HashMap<>(); // /* // * Cache of methods that we've found in particular classes // */ // private static final Map<Class<?>, Map<String, Method>> loadedMethods = new HashMap<>(); // /* // * The server version string to location NMS & OBC classes // */ // private static String versionString; // // /** // * Gets the version string for NMS &amp; OBC class paths // * // * @return The version string of OBC and NMS packages // */ // public static String getVersion() { // if (versionString == null) { // String name = Bukkit.getServer().getClass().getPackage().getName(); // versionString = name.substring(name.lastIndexOf('.') + 1) + "."; // } // // return versionString; // } // // /** // * Get a class from the org.bukkit.craftbukkit package // * // * @param obcClassName the path to the class // * @return the found class at the specified path // */ // public static Class<?> getOBCClass(String obcClassName) { // if (loadedOBCClasses.containsKey(obcClassName)) { // return loadedOBCClasses.get(obcClassName); // } // // String clazzName = "org.bukkit.craftbukkit." + getVersion() + obcClassName; // Class<?> clazz; // // try { // clazz = Class.forName(clazzName); // } catch (Throwable t) { // t.printStackTrace(); // loadedOBCClasses.put(obcClassName, null); // return null; // } // // loadedOBCClasses.put(obcClassName, clazz); // return clazz; // } // // /** // * Get a method from a class that has the specific parameters // * // * @param clazz The class we are searching // * @param methodName The name of the method // * @param params Any parameters that the method has // * @return The method with appropriate parameters // */ // public static Method getMethod(Class<?> clazz, String methodName, Class<?>... params) { // if (!loadedMethods.containsKey(clazz)) { // loadedMethods.put(clazz, new HashMap<>()); // } // // Map<String, Method> methods = loadedMethods.get(clazz); // // if (methods.containsKey(methodName)) { // return methods.get(methodName); // } // // try { // Method method = clazz.getDeclaredMethod(methodName, params); // if (method != null) method.setAccessible(true); // methods.put(methodName, method); // loadedMethods.put(clazz, methods); // return method; // } catch (Exception e) { // e.printStackTrace(); // methods.put(methodName, null); // loadedMethods.put(clazz, methods); // return null; // } // } // // // /** // * get all declared fields in a class and its' super class. // * // * @param clz target class // * @return a List of Field objects declared by clz. // * @since 7.2 // */ // public static List<Field> getAllFields(Class<?> clz) { // List<Field> fields = new ArrayList<>(); // return getAllFields(clz, fields); // } // // private static List<Field> getAllFields(Class<?> clz, List<Field> list) { // Collections.addAll(list, clz.getDeclaredFields()); // // Class<?> supClz = clz.getSuperclass(); // if (supClz == null) { // return list; // } else { // return getAllFields(supClz, list); // } // } // }
import cat.nyaa.nyaacore.configuration.annotation.Deserializer; import cat.nyaa.nyaacore.utils.ReflectionUtils; import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.logging.Level;
package cat.nyaa.nyaacore.configuration; /** * Serialize or Deserialize objects into ConfigurationSection */ public interface ISerializable { @SuppressWarnings({"unchecked", "rawtypes"}) static void deserialize(ConfigurationSection config, Object obj) { Class<?> clz = obj.getClass();
// Path: src/main/java/cat/nyaa/nyaacore/utils/ReflectionUtils.java // public final class ReflectionUtils { // // /* // * Cache of NMS classes that we've searched for // */ // private static final Map<String, Class<?>> loadedNMSClasses = new HashMap<>(); // /* // * Cache of OBS classes that we've searched for // */ // private static final Map<String, Class<?>> loadedOBCClasses = new HashMap<>(); // /* // * Cache of methods that we've found in particular classes // */ // private static final Map<Class<?>, Map<String, Method>> loadedMethods = new HashMap<>(); // /* // * The server version string to location NMS & OBC classes // */ // private static String versionString; // // /** // * Gets the version string for NMS &amp; OBC class paths // * // * @return The version string of OBC and NMS packages // */ // public static String getVersion() { // if (versionString == null) { // String name = Bukkit.getServer().getClass().getPackage().getName(); // versionString = name.substring(name.lastIndexOf('.') + 1) + "."; // } // // return versionString; // } // // /** // * Get a class from the org.bukkit.craftbukkit package // * // * @param obcClassName the path to the class // * @return the found class at the specified path // */ // public static Class<?> getOBCClass(String obcClassName) { // if (loadedOBCClasses.containsKey(obcClassName)) { // return loadedOBCClasses.get(obcClassName); // } // // String clazzName = "org.bukkit.craftbukkit." + getVersion() + obcClassName; // Class<?> clazz; // // try { // clazz = Class.forName(clazzName); // } catch (Throwable t) { // t.printStackTrace(); // loadedOBCClasses.put(obcClassName, null); // return null; // } // // loadedOBCClasses.put(obcClassName, clazz); // return clazz; // } // // /** // * Get a method from a class that has the specific parameters // * // * @param clazz The class we are searching // * @param methodName The name of the method // * @param params Any parameters that the method has // * @return The method with appropriate parameters // */ // public static Method getMethod(Class<?> clazz, String methodName, Class<?>... params) { // if (!loadedMethods.containsKey(clazz)) { // loadedMethods.put(clazz, new HashMap<>()); // } // // Map<String, Method> methods = loadedMethods.get(clazz); // // if (methods.containsKey(methodName)) { // return methods.get(methodName); // } // // try { // Method method = clazz.getDeclaredMethod(methodName, params); // if (method != null) method.setAccessible(true); // methods.put(methodName, method); // loadedMethods.put(clazz, methods); // return method; // } catch (Exception e) { // e.printStackTrace(); // methods.put(methodName, null); // loadedMethods.put(clazz, methods); // return null; // } // } // // // /** // * get all declared fields in a class and its' super class. // * // * @param clz target class // * @return a List of Field objects declared by clz. // * @since 7.2 // */ // public static List<Field> getAllFields(Class<?> clz) { // List<Field> fields = new ArrayList<>(); // return getAllFields(clz, fields); // } // // private static List<Field> getAllFields(Class<?> clz, List<Field> list) { // Collections.addAll(list, clz.getDeclaredFields()); // // Class<?> supClz = clz.getSuperclass(); // if (supClz == null) { // return list; // } else { // return getAllFields(supClz, list); // } // } // } // Path: src/main/java/cat/nyaa/nyaacore/configuration/ISerializable.java import cat.nyaa.nyaacore.configuration.annotation.Deserializer; import cat.nyaa.nyaacore.utils.ReflectionUtils; import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.logging.Level; package cat.nyaa.nyaacore.configuration; /** * Serialize or Deserialize objects into ConfigurationSection */ public interface ISerializable { @SuppressWarnings({"unchecked", "rawtypes"}) static void deserialize(ConfigurationSection config, Object obj) { Class<?> clz = obj.getClass();
List<Field> fields = ReflectionUtils.getAllFields(clz);
NyaaCat/NyaaCore
src/main/java/cat/nyaa/nyaacore/orm/RollbackGuard.java
// Path: src/main/java/cat/nyaa/nyaacore/orm/backends/IConnectedDatabase.java // public interface IConnectedDatabase extends AutoCloseable { // /** // * Get underlying JDBC connection. Easily gets messed up. Avoid if you can. // * // * @return // */ // Connection getConnection(); // // <T> ITypedTable<T> getTable(Class<T> recordClass); // // /** // * @param recordClass // * @param <T> // * @return // */ // <T> ITypedTable<T> getUnverifiedTable(Class<T> recordClass); // // @Override // void close() throws SQLException; // // boolean verifySchema(String tableName, Class recordClass); // // /** // * Execute a SQL file bundled with some plugin, using the default Connection. // * // * @param filename full file name, including extension, in resources/sql folder // * @param replacementMap {{key}} in the file will be replaced by value. Ignored if null. NOTE: sql injection will happen // * @param cls class of desired object // * @param parameters JDBC's positional parametrized query. Java Type // * @return the result set, null if cls is null. // */ // <T> List<T> queryBundledAs(Plugin plugin, String filename, Map<String, String> replacementMap, Class<T> cls, Object... parameters); // }
import cat.nyaa.nyaacore.orm.backends.IConnectedDatabase; import java.sql.Connection; import java.sql.SQLException;
package cat.nyaa.nyaacore.orm; /** * This provides a easy way to rollback database in case of Java program exceptions. * You are not expected to use this for real transactions. * <p> * Here is the use case: * <pre> * try (RollbackGuard guard = new RollbackGuard(db)) { * // something could throw exception * guard.commit(); * } * </pre> * <p> * If exception is thrown and guard is not committed, the guard will automatically rollback the connection. */ public class RollbackGuard implements AutoCloseable { private final Connection conn; private boolean needRollbackOnClose = false;
// Path: src/main/java/cat/nyaa/nyaacore/orm/backends/IConnectedDatabase.java // public interface IConnectedDatabase extends AutoCloseable { // /** // * Get underlying JDBC connection. Easily gets messed up. Avoid if you can. // * // * @return // */ // Connection getConnection(); // // <T> ITypedTable<T> getTable(Class<T> recordClass); // // /** // * @param recordClass // * @param <T> // * @return // */ // <T> ITypedTable<T> getUnverifiedTable(Class<T> recordClass); // // @Override // void close() throws SQLException; // // boolean verifySchema(String tableName, Class recordClass); // // /** // * Execute a SQL file bundled with some plugin, using the default Connection. // * // * @param filename full file name, including extension, in resources/sql folder // * @param replacementMap {{key}} in the file will be replaced by value. Ignored if null. NOTE: sql injection will happen // * @param cls class of desired object // * @param parameters JDBC's positional parametrized query. Java Type // * @return the result set, null if cls is null. // */ // <T> List<T> queryBundledAs(Plugin plugin, String filename, Map<String, String> replacementMap, Class<T> cls, Object... parameters); // } // Path: src/main/java/cat/nyaa/nyaacore/orm/RollbackGuard.java import cat.nyaa.nyaacore.orm.backends.IConnectedDatabase; import java.sql.Connection; import java.sql.SQLException; package cat.nyaa.nyaacore.orm; /** * This provides a easy way to rollback database in case of Java program exceptions. * You are not expected to use this for real transactions. * <p> * Here is the use case: * <pre> * try (RollbackGuard guard = new RollbackGuard(db)) { * // something could throw exception * guard.commit(); * } * </pre> * <p> * If exception is thrown and guard is not committed, the guard will automatically rollback the connection. */ public class RollbackGuard implements AutoCloseable { private final Connection conn; private boolean needRollbackOnClose = false;
public RollbackGuard(IConnectedDatabase db) {
Avarel/Kaiper
Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/GroupParser.java
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/lexer/TokenType.java // public enum TokenType { // // PAIRS // LEFT_PAREN, // RIGHT_PAREN, // // LEFT_BRACKET, // RIGHT_BRACKET, // // LEFT_BRACE, // RIGHT_BRACE, // // OPTIONAL_ASSIGN, // ELVIS, // // // ASSIGNMENT // ASSIGN, // // // TYPES // INT, // NUMBER, // BOOLEAN, // FUNCTION, // STRING, // ATOM, // // // ARITHMETIC // PLUS, // MINUS, // ASTERISK, // SLASH, // BACKSLASH, // CARET, // PERCENT, // // // RELATIONAL // EQUALS, // NOT_EQUAL, // GT, // GTE, // LT, // LTE, // OR, // AND, // // // BOOLEAN // AMPERSAND, // VERTICAL_BAR, // // // MISC // REST, // RANGE_TO, // PIPE_FORWARD, // PIPE_BACKWARD, // SHIFT_RIGHT, // SHIFT_LEFT, // ARROW, // TILDE, // BANG, // QUESTION, // COLON, // COMMA, // DOT, // // UNDERSCORE, // // // SCRIPT // MODULE, // TYPE, // IDENTIFIER, // NULL, // LET, // RETURN, // IF, // ELSE, // FOR, // // LINE, // EOF, // }
import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.lexer.TokenType; import xyz.avarel.kaiper.parser.KaiperParser; import xyz.avarel.kaiper.parser.PrefixParser;
/* * 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 xyz.avarel.kaiper.parser.parslets; public class GroupParser implements PrefixParser { @Override public Expr parse(KaiperParser parser, Token token) { Expr expr = parser.parseExpr();
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/lexer/TokenType.java // public enum TokenType { // // PAIRS // LEFT_PAREN, // RIGHT_PAREN, // // LEFT_BRACKET, // RIGHT_BRACKET, // // LEFT_BRACE, // RIGHT_BRACE, // // OPTIONAL_ASSIGN, // ELVIS, // // // ASSIGNMENT // ASSIGN, // // // TYPES // INT, // NUMBER, // BOOLEAN, // FUNCTION, // STRING, // ATOM, // // // ARITHMETIC // PLUS, // MINUS, // ASTERISK, // SLASH, // BACKSLASH, // CARET, // PERCENT, // // // RELATIONAL // EQUALS, // NOT_EQUAL, // GT, // GTE, // LT, // LTE, // OR, // AND, // // // BOOLEAN // AMPERSAND, // VERTICAL_BAR, // // // MISC // REST, // RANGE_TO, // PIPE_FORWARD, // PIPE_BACKWARD, // SHIFT_RIGHT, // SHIFT_LEFT, // ARROW, // TILDE, // BANG, // QUESTION, // COLON, // COMMA, // DOT, // // UNDERSCORE, // // // SCRIPT // MODULE, // TYPE, // IDENTIFIER, // NULL, // LET, // RETURN, // IF, // ELSE, // FOR, // // LINE, // EOF, // } // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/GroupParser.java import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.lexer.TokenType; import xyz.avarel.kaiper.parser.KaiperParser; import xyz.avarel.kaiper.parser.PrefixParser; /* * 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 xyz.avarel.kaiper.parser.parslets; public class GroupParser implements PrefixParser { @Override public Expr parse(KaiperParser parser, Token token) { Expr expr = parser.parseExpr();
parser.eat(TokenType.RIGHT_PAREN);
Avarel/Kaiper
Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/operators/BinaryOperatorParser.java
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/DecimalNode.java // public class DecimalNode extends Single { // private final double value; // // public DecimalNode(Position position, double value) { // super(position); // this.value = value; // } // // public double getValue() { // return value; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public String toString() { // return String.valueOf(value); // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/IntNode.java // public class IntNode extends Single { // private final int value; // // public IntNode(Position position, int value) { // super(position); // this.value = value; // } // // public int getValue() { // return value; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public String toString() { // return String.valueOf(value); // } // } // // Path: Kaiper-Common/src/main/java/xyz/avarel/kaiper/operations/BinaryOperatorType.java // public enum BinaryOperatorType { // PLUS, // MINUS, // TIMES, // DIVIDE, // MODULUS, // POWER, // EQUALS, // NOT_EQUALS, // GREATER_THAN, // GREATER_THAN_EQUAL, // LESS_THAN, // LESS_THAN_EQUAL, // AND, // OR, // SHL, // SHR, // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/BinaryParser.java // public abstract class BinaryParser implements InfixParser { // private final int precedence; // private final boolean leftAssoc; // // public BinaryParser(int precedence) { // this(precedence, true); // } // // public BinaryParser(int precedence, boolean leftAssoc) { // this.precedence = precedence; // this.leftAssoc = leftAssoc; // } // // @Override // public Expr parse(KaiperParser parser, Expr left, Token token) { // if (!(left instanceof Single)) { // throw new SyntaxException("Internal compiler error", token.getPosition()); // } // return parse(parser, (Single) left, token); // } // // public abstract Expr parse(KaiperParser parser, Single left, Token token); // // @Override // public int getPrecedence() { // return precedence; // } // // public boolean isLeftAssoc() { // return leftAssoc; // } // }
import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.ast.Single; import xyz.avarel.kaiper.ast.operations.BinaryOperation; import xyz.avarel.kaiper.ast.value.BooleanNode; import xyz.avarel.kaiper.ast.value.DecimalNode; import xyz.avarel.kaiper.ast.value.IntNode; import xyz.avarel.kaiper.exceptions.SyntaxException; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.operations.BinaryOperatorType; import xyz.avarel.kaiper.parser.BinaryParser; import xyz.avarel.kaiper.parser.KaiperParser;
/* * 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 xyz.avarel.kaiper.parser.parslets.operators; public class BinaryOperatorParser extends BinaryParser { private final BinaryOperatorType operator; public BinaryOperatorParser(int precedence, boolean leftAssoc, BinaryOperatorType operator) { super(precedence, leftAssoc); this.operator = operator; } @Override public Expr parse(KaiperParser parser, Single left, Token token) { Single right = parser.parseSingle(getPrecedence() - (isLeftAssoc() ? 0 : 1));
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/DecimalNode.java // public class DecimalNode extends Single { // private final double value; // // public DecimalNode(Position position, double value) { // super(position); // this.value = value; // } // // public double getValue() { // return value; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public String toString() { // return String.valueOf(value); // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/IntNode.java // public class IntNode extends Single { // private final int value; // // public IntNode(Position position, int value) { // super(position); // this.value = value; // } // // public int getValue() { // return value; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public String toString() { // return String.valueOf(value); // } // } // // Path: Kaiper-Common/src/main/java/xyz/avarel/kaiper/operations/BinaryOperatorType.java // public enum BinaryOperatorType { // PLUS, // MINUS, // TIMES, // DIVIDE, // MODULUS, // POWER, // EQUALS, // NOT_EQUALS, // GREATER_THAN, // GREATER_THAN_EQUAL, // LESS_THAN, // LESS_THAN_EQUAL, // AND, // OR, // SHL, // SHR, // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/BinaryParser.java // public abstract class BinaryParser implements InfixParser { // private final int precedence; // private final boolean leftAssoc; // // public BinaryParser(int precedence) { // this(precedence, true); // } // // public BinaryParser(int precedence, boolean leftAssoc) { // this.precedence = precedence; // this.leftAssoc = leftAssoc; // } // // @Override // public Expr parse(KaiperParser parser, Expr left, Token token) { // if (!(left instanceof Single)) { // throw new SyntaxException("Internal compiler error", token.getPosition()); // } // return parse(parser, (Single) left, token); // } // // public abstract Expr parse(KaiperParser parser, Single left, Token token); // // @Override // public int getPrecedence() { // return precedence; // } // // public boolean isLeftAssoc() { // return leftAssoc; // } // } // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/operators/BinaryOperatorParser.java import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.ast.Single; import xyz.avarel.kaiper.ast.operations.BinaryOperation; import xyz.avarel.kaiper.ast.value.BooleanNode; import xyz.avarel.kaiper.ast.value.DecimalNode; import xyz.avarel.kaiper.ast.value.IntNode; import xyz.avarel.kaiper.exceptions.SyntaxException; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.operations.BinaryOperatorType; import xyz.avarel.kaiper.parser.BinaryParser; import xyz.avarel.kaiper.parser.KaiperParser; /* * 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 xyz.avarel.kaiper.parser.parslets.operators; public class BinaryOperatorParser extends BinaryParser { private final BinaryOperatorType operator; public BinaryOperatorParser(int precedence, boolean leftAssoc, BinaryOperatorType operator) { super(precedence, leftAssoc); this.operator = operator; } @Override public Expr parse(KaiperParser parser, Single left, Token token) { Single right = parser.parseSingle(getPrecedence() - (isLeftAssoc() ? 0 : 1));
if ((left instanceof IntNode || left instanceof DecimalNode)
Avarel/Kaiper
Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/operators/BinaryOperatorParser.java
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/DecimalNode.java // public class DecimalNode extends Single { // private final double value; // // public DecimalNode(Position position, double value) { // super(position); // this.value = value; // } // // public double getValue() { // return value; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public String toString() { // return String.valueOf(value); // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/IntNode.java // public class IntNode extends Single { // private final int value; // // public IntNode(Position position, int value) { // super(position); // this.value = value; // } // // public int getValue() { // return value; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public String toString() { // return String.valueOf(value); // } // } // // Path: Kaiper-Common/src/main/java/xyz/avarel/kaiper/operations/BinaryOperatorType.java // public enum BinaryOperatorType { // PLUS, // MINUS, // TIMES, // DIVIDE, // MODULUS, // POWER, // EQUALS, // NOT_EQUALS, // GREATER_THAN, // GREATER_THAN_EQUAL, // LESS_THAN, // LESS_THAN_EQUAL, // AND, // OR, // SHL, // SHR, // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/BinaryParser.java // public abstract class BinaryParser implements InfixParser { // private final int precedence; // private final boolean leftAssoc; // // public BinaryParser(int precedence) { // this(precedence, true); // } // // public BinaryParser(int precedence, boolean leftAssoc) { // this.precedence = precedence; // this.leftAssoc = leftAssoc; // } // // @Override // public Expr parse(KaiperParser parser, Expr left, Token token) { // if (!(left instanceof Single)) { // throw new SyntaxException("Internal compiler error", token.getPosition()); // } // return parse(parser, (Single) left, token); // } // // public abstract Expr parse(KaiperParser parser, Single left, Token token); // // @Override // public int getPrecedence() { // return precedence; // } // // public boolean isLeftAssoc() { // return leftAssoc; // } // }
import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.ast.Single; import xyz.avarel.kaiper.ast.operations.BinaryOperation; import xyz.avarel.kaiper.ast.value.BooleanNode; import xyz.avarel.kaiper.ast.value.DecimalNode; import xyz.avarel.kaiper.ast.value.IntNode; import xyz.avarel.kaiper.exceptions.SyntaxException; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.operations.BinaryOperatorType; import xyz.avarel.kaiper.parser.BinaryParser; import xyz.avarel.kaiper.parser.KaiperParser;
/* * 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 xyz.avarel.kaiper.parser.parslets.operators; public class BinaryOperatorParser extends BinaryParser { private final BinaryOperatorType operator; public BinaryOperatorParser(int precedence, boolean leftAssoc, BinaryOperatorType operator) { super(precedence, leftAssoc); this.operator = operator; } @Override public Expr parse(KaiperParser parser, Single left, Token token) { Single right = parser.parseSingle(getPrecedence() - (isLeftAssoc() ? 0 : 1));
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/DecimalNode.java // public class DecimalNode extends Single { // private final double value; // // public DecimalNode(Position position, double value) { // super(position); // this.value = value; // } // // public double getValue() { // return value; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public String toString() { // return String.valueOf(value); // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/IntNode.java // public class IntNode extends Single { // private final int value; // // public IntNode(Position position, int value) { // super(position); // this.value = value; // } // // public int getValue() { // return value; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public String toString() { // return String.valueOf(value); // } // } // // Path: Kaiper-Common/src/main/java/xyz/avarel/kaiper/operations/BinaryOperatorType.java // public enum BinaryOperatorType { // PLUS, // MINUS, // TIMES, // DIVIDE, // MODULUS, // POWER, // EQUALS, // NOT_EQUALS, // GREATER_THAN, // GREATER_THAN_EQUAL, // LESS_THAN, // LESS_THAN_EQUAL, // AND, // OR, // SHL, // SHR, // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/BinaryParser.java // public abstract class BinaryParser implements InfixParser { // private final int precedence; // private final boolean leftAssoc; // // public BinaryParser(int precedence) { // this(precedence, true); // } // // public BinaryParser(int precedence, boolean leftAssoc) { // this.precedence = precedence; // this.leftAssoc = leftAssoc; // } // // @Override // public Expr parse(KaiperParser parser, Expr left, Token token) { // if (!(left instanceof Single)) { // throw new SyntaxException("Internal compiler error", token.getPosition()); // } // return parse(parser, (Single) left, token); // } // // public abstract Expr parse(KaiperParser parser, Single left, Token token); // // @Override // public int getPrecedence() { // return precedence; // } // // public boolean isLeftAssoc() { // return leftAssoc; // } // } // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/operators/BinaryOperatorParser.java import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.ast.Single; import xyz.avarel.kaiper.ast.operations.BinaryOperation; import xyz.avarel.kaiper.ast.value.BooleanNode; import xyz.avarel.kaiper.ast.value.DecimalNode; import xyz.avarel.kaiper.ast.value.IntNode; import xyz.avarel.kaiper.exceptions.SyntaxException; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.operations.BinaryOperatorType; import xyz.avarel.kaiper.parser.BinaryParser; import xyz.avarel.kaiper.parser.KaiperParser; /* * 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 xyz.avarel.kaiper.parser.parslets.operators; public class BinaryOperatorParser extends BinaryParser { private final BinaryOperatorType operator; public BinaryOperatorParser(int precedence, boolean leftAssoc, BinaryOperatorType operator) { super(precedence, leftAssoc); this.operator = operator; } @Override public Expr parse(KaiperParser parser, Single left, Token token) { Single right = parser.parseSingle(getPrecedence() - (isLeftAssoc() ? 0 : 1));
if ((left instanceof IntNode || left instanceof DecimalNode)
Avarel/Kaiper
Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/ElvisParser.java
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/flow/ConditionalExpr.java // public class ConditionalExpr extends Single { // private final Single condition; // private final Expr ifBranch; // private final Expr elseBranch; // // public ConditionalExpr(Position position, Single condition, Expr ifBranch, Expr elseBranch) { // super(position); // this.condition = condition; // this.ifBranch = ifBranch; // this.elseBranch = elseBranch; // } // // public Single getCondition() { // return condition; // } // // public Expr getIfBranch() { // return ifBranch; // } // // public Expr getElseBranch() { // return elseBranch; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public void ast(StringBuilder builder, String indent, boolean isTail) { // return if (sin(0) == 0) sin(50) else false // builder.append(indent).append(isTail ? "└── " : "├── ").append("if"); // // builder.append('\n'); // condition.ast("condition", builder, indent + (isTail ? " " : "│ "), false); // // builder.append('\n'); // ifBranch.ast("true", builder, indent + (isTail ? " " : "│ "), elseBranch == null); // // if (elseBranch != null) { // builder.append('\n'); // elseBranch.ast("false", builder, indent + (isTail ? " " : "│ "), true); // } // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/NullNode.java // public class NullNode extends Single { // public static final NullNode VALUE = new NullNode(); // // private NullNode() { // super(null); // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // } // // Path: Kaiper-Common/src/main/java/xyz/avarel/kaiper/operations/BinaryOperatorType.java // public enum BinaryOperatorType { // PLUS, // MINUS, // TIMES, // DIVIDE, // MODULUS, // POWER, // EQUALS, // NOT_EQUALS, // GREATER_THAN, // GREATER_THAN_EQUAL, // LESS_THAN, // LESS_THAN_EQUAL, // AND, // OR, // SHL, // SHR, // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/BinaryParser.java // public abstract class BinaryParser implements InfixParser { // private final int precedence; // private final boolean leftAssoc; // // public BinaryParser(int precedence) { // this(precedence, true); // } // // public BinaryParser(int precedence, boolean leftAssoc) { // this.precedence = precedence; // this.leftAssoc = leftAssoc; // } // // @Override // public Expr parse(KaiperParser parser, Expr left, Token token) { // if (!(left instanceof Single)) { // throw new SyntaxException("Internal compiler error", token.getPosition()); // } // return parse(parser, (Single) left, token); // } // // public abstract Expr parse(KaiperParser parser, Single left, Token token); // // @Override // public int getPrecedence() { // return precedence; // } // // public boolean isLeftAssoc() { // return leftAssoc; // } // }
import xyz.avarel.kaiper.Precedence; import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.ast.Single; import xyz.avarel.kaiper.ast.flow.ConditionalExpr; import xyz.avarel.kaiper.ast.operations.BinaryOperation; import xyz.avarel.kaiper.ast.value.NullNode; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.operations.BinaryOperatorType; import xyz.avarel.kaiper.parser.BinaryParser; import xyz.avarel.kaiper.parser.KaiperParser;
/* * 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 xyz.avarel.kaiper.parser.parslets; public class ElvisParser extends BinaryParser { public ElvisParser() { super(Precedence.INFIX); } @Override public Expr parse(KaiperParser parser, Single left, Token token) {
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/flow/ConditionalExpr.java // public class ConditionalExpr extends Single { // private final Single condition; // private final Expr ifBranch; // private final Expr elseBranch; // // public ConditionalExpr(Position position, Single condition, Expr ifBranch, Expr elseBranch) { // super(position); // this.condition = condition; // this.ifBranch = ifBranch; // this.elseBranch = elseBranch; // } // // public Single getCondition() { // return condition; // } // // public Expr getIfBranch() { // return ifBranch; // } // // public Expr getElseBranch() { // return elseBranch; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public void ast(StringBuilder builder, String indent, boolean isTail) { // return if (sin(0) == 0) sin(50) else false // builder.append(indent).append(isTail ? "└── " : "├── ").append("if"); // // builder.append('\n'); // condition.ast("condition", builder, indent + (isTail ? " " : "│ "), false); // // builder.append('\n'); // ifBranch.ast("true", builder, indent + (isTail ? " " : "│ "), elseBranch == null); // // if (elseBranch != null) { // builder.append('\n'); // elseBranch.ast("false", builder, indent + (isTail ? " " : "│ "), true); // } // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/NullNode.java // public class NullNode extends Single { // public static final NullNode VALUE = new NullNode(); // // private NullNode() { // super(null); // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // } // // Path: Kaiper-Common/src/main/java/xyz/avarel/kaiper/operations/BinaryOperatorType.java // public enum BinaryOperatorType { // PLUS, // MINUS, // TIMES, // DIVIDE, // MODULUS, // POWER, // EQUALS, // NOT_EQUALS, // GREATER_THAN, // GREATER_THAN_EQUAL, // LESS_THAN, // LESS_THAN_EQUAL, // AND, // OR, // SHL, // SHR, // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/BinaryParser.java // public abstract class BinaryParser implements InfixParser { // private final int precedence; // private final boolean leftAssoc; // // public BinaryParser(int precedence) { // this(precedence, true); // } // // public BinaryParser(int precedence, boolean leftAssoc) { // this.precedence = precedence; // this.leftAssoc = leftAssoc; // } // // @Override // public Expr parse(KaiperParser parser, Expr left, Token token) { // if (!(left instanceof Single)) { // throw new SyntaxException("Internal compiler error", token.getPosition()); // } // return parse(parser, (Single) left, token); // } // // public abstract Expr parse(KaiperParser parser, Single left, Token token); // // @Override // public int getPrecedence() { // return precedence; // } // // public boolean isLeftAssoc() { // return leftAssoc; // } // } // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/ElvisParser.java import xyz.avarel.kaiper.Precedence; import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.ast.Single; import xyz.avarel.kaiper.ast.flow.ConditionalExpr; import xyz.avarel.kaiper.ast.operations.BinaryOperation; import xyz.avarel.kaiper.ast.value.NullNode; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.operations.BinaryOperatorType; import xyz.avarel.kaiper.parser.BinaryParser; import xyz.avarel.kaiper.parser.KaiperParser; /* * 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 xyz.avarel.kaiper.parser.parslets; public class ElvisParser extends BinaryParser { public ElvisParser() { super(Precedence.INFIX); } @Override public Expr parse(KaiperParser parser, Single left, Token token) {
return new ConditionalExpr(
Avarel/Kaiper
Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/ElvisParser.java
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/flow/ConditionalExpr.java // public class ConditionalExpr extends Single { // private final Single condition; // private final Expr ifBranch; // private final Expr elseBranch; // // public ConditionalExpr(Position position, Single condition, Expr ifBranch, Expr elseBranch) { // super(position); // this.condition = condition; // this.ifBranch = ifBranch; // this.elseBranch = elseBranch; // } // // public Single getCondition() { // return condition; // } // // public Expr getIfBranch() { // return ifBranch; // } // // public Expr getElseBranch() { // return elseBranch; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public void ast(StringBuilder builder, String indent, boolean isTail) { // return if (sin(0) == 0) sin(50) else false // builder.append(indent).append(isTail ? "└── " : "├── ").append("if"); // // builder.append('\n'); // condition.ast("condition", builder, indent + (isTail ? " " : "│ "), false); // // builder.append('\n'); // ifBranch.ast("true", builder, indent + (isTail ? " " : "│ "), elseBranch == null); // // if (elseBranch != null) { // builder.append('\n'); // elseBranch.ast("false", builder, indent + (isTail ? " " : "│ "), true); // } // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/NullNode.java // public class NullNode extends Single { // public static final NullNode VALUE = new NullNode(); // // private NullNode() { // super(null); // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // } // // Path: Kaiper-Common/src/main/java/xyz/avarel/kaiper/operations/BinaryOperatorType.java // public enum BinaryOperatorType { // PLUS, // MINUS, // TIMES, // DIVIDE, // MODULUS, // POWER, // EQUALS, // NOT_EQUALS, // GREATER_THAN, // GREATER_THAN_EQUAL, // LESS_THAN, // LESS_THAN_EQUAL, // AND, // OR, // SHL, // SHR, // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/BinaryParser.java // public abstract class BinaryParser implements InfixParser { // private final int precedence; // private final boolean leftAssoc; // // public BinaryParser(int precedence) { // this(precedence, true); // } // // public BinaryParser(int precedence, boolean leftAssoc) { // this.precedence = precedence; // this.leftAssoc = leftAssoc; // } // // @Override // public Expr parse(KaiperParser parser, Expr left, Token token) { // if (!(left instanceof Single)) { // throw new SyntaxException("Internal compiler error", token.getPosition()); // } // return parse(parser, (Single) left, token); // } // // public abstract Expr parse(KaiperParser parser, Single left, Token token); // // @Override // public int getPrecedence() { // return precedence; // } // // public boolean isLeftAssoc() { // return leftAssoc; // } // }
import xyz.avarel.kaiper.Precedence; import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.ast.Single; import xyz.avarel.kaiper.ast.flow.ConditionalExpr; import xyz.avarel.kaiper.ast.operations.BinaryOperation; import xyz.avarel.kaiper.ast.value.NullNode; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.operations.BinaryOperatorType; import xyz.avarel.kaiper.parser.BinaryParser; import xyz.avarel.kaiper.parser.KaiperParser;
/* * 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 xyz.avarel.kaiper.parser.parslets; public class ElvisParser extends BinaryParser { public ElvisParser() { super(Precedence.INFIX); } @Override public Expr parse(KaiperParser parser, Single left, Token token) { return new ConditionalExpr( token.getPosition(), new BinaryOperation( token.getPosition(), left,
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/flow/ConditionalExpr.java // public class ConditionalExpr extends Single { // private final Single condition; // private final Expr ifBranch; // private final Expr elseBranch; // // public ConditionalExpr(Position position, Single condition, Expr ifBranch, Expr elseBranch) { // super(position); // this.condition = condition; // this.ifBranch = ifBranch; // this.elseBranch = elseBranch; // } // // public Single getCondition() { // return condition; // } // // public Expr getIfBranch() { // return ifBranch; // } // // public Expr getElseBranch() { // return elseBranch; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public void ast(StringBuilder builder, String indent, boolean isTail) { // return if (sin(0) == 0) sin(50) else false // builder.append(indent).append(isTail ? "└── " : "├── ").append("if"); // // builder.append('\n'); // condition.ast("condition", builder, indent + (isTail ? " " : "│ "), false); // // builder.append('\n'); // ifBranch.ast("true", builder, indent + (isTail ? " " : "│ "), elseBranch == null); // // if (elseBranch != null) { // builder.append('\n'); // elseBranch.ast("false", builder, indent + (isTail ? " " : "│ "), true); // } // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/NullNode.java // public class NullNode extends Single { // public static final NullNode VALUE = new NullNode(); // // private NullNode() { // super(null); // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // } // // Path: Kaiper-Common/src/main/java/xyz/avarel/kaiper/operations/BinaryOperatorType.java // public enum BinaryOperatorType { // PLUS, // MINUS, // TIMES, // DIVIDE, // MODULUS, // POWER, // EQUALS, // NOT_EQUALS, // GREATER_THAN, // GREATER_THAN_EQUAL, // LESS_THAN, // LESS_THAN_EQUAL, // AND, // OR, // SHL, // SHR, // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/BinaryParser.java // public abstract class BinaryParser implements InfixParser { // private final int precedence; // private final boolean leftAssoc; // // public BinaryParser(int precedence) { // this(precedence, true); // } // // public BinaryParser(int precedence, boolean leftAssoc) { // this.precedence = precedence; // this.leftAssoc = leftAssoc; // } // // @Override // public Expr parse(KaiperParser parser, Expr left, Token token) { // if (!(left instanceof Single)) { // throw new SyntaxException("Internal compiler error", token.getPosition()); // } // return parse(parser, (Single) left, token); // } // // public abstract Expr parse(KaiperParser parser, Single left, Token token); // // @Override // public int getPrecedence() { // return precedence; // } // // public boolean isLeftAssoc() { // return leftAssoc; // } // } // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/ElvisParser.java import xyz.avarel.kaiper.Precedence; import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.ast.Single; import xyz.avarel.kaiper.ast.flow.ConditionalExpr; import xyz.avarel.kaiper.ast.operations.BinaryOperation; import xyz.avarel.kaiper.ast.value.NullNode; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.operations.BinaryOperatorType; import xyz.avarel.kaiper.parser.BinaryParser; import xyz.avarel.kaiper.parser.KaiperParser; /* * 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 xyz.avarel.kaiper.parser.parslets; public class ElvisParser extends BinaryParser { public ElvisParser() { super(Precedence.INFIX); } @Override public Expr parse(KaiperParser parser, Single left, Token token) { return new ConditionalExpr( token.getPosition(), new BinaryOperation( token.getPosition(), left,
NullNode.VALUE,
Avarel/Kaiper
Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/ElvisParser.java
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/flow/ConditionalExpr.java // public class ConditionalExpr extends Single { // private final Single condition; // private final Expr ifBranch; // private final Expr elseBranch; // // public ConditionalExpr(Position position, Single condition, Expr ifBranch, Expr elseBranch) { // super(position); // this.condition = condition; // this.ifBranch = ifBranch; // this.elseBranch = elseBranch; // } // // public Single getCondition() { // return condition; // } // // public Expr getIfBranch() { // return ifBranch; // } // // public Expr getElseBranch() { // return elseBranch; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public void ast(StringBuilder builder, String indent, boolean isTail) { // return if (sin(0) == 0) sin(50) else false // builder.append(indent).append(isTail ? "└── " : "├── ").append("if"); // // builder.append('\n'); // condition.ast("condition", builder, indent + (isTail ? " " : "│ "), false); // // builder.append('\n'); // ifBranch.ast("true", builder, indent + (isTail ? " " : "│ "), elseBranch == null); // // if (elseBranch != null) { // builder.append('\n'); // elseBranch.ast("false", builder, indent + (isTail ? " " : "│ "), true); // } // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/NullNode.java // public class NullNode extends Single { // public static final NullNode VALUE = new NullNode(); // // private NullNode() { // super(null); // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // } // // Path: Kaiper-Common/src/main/java/xyz/avarel/kaiper/operations/BinaryOperatorType.java // public enum BinaryOperatorType { // PLUS, // MINUS, // TIMES, // DIVIDE, // MODULUS, // POWER, // EQUALS, // NOT_EQUALS, // GREATER_THAN, // GREATER_THAN_EQUAL, // LESS_THAN, // LESS_THAN_EQUAL, // AND, // OR, // SHL, // SHR, // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/BinaryParser.java // public abstract class BinaryParser implements InfixParser { // private final int precedence; // private final boolean leftAssoc; // // public BinaryParser(int precedence) { // this(precedence, true); // } // // public BinaryParser(int precedence, boolean leftAssoc) { // this.precedence = precedence; // this.leftAssoc = leftAssoc; // } // // @Override // public Expr parse(KaiperParser parser, Expr left, Token token) { // if (!(left instanceof Single)) { // throw new SyntaxException("Internal compiler error", token.getPosition()); // } // return parse(parser, (Single) left, token); // } // // public abstract Expr parse(KaiperParser parser, Single left, Token token); // // @Override // public int getPrecedence() { // return precedence; // } // // public boolean isLeftAssoc() { // return leftAssoc; // } // }
import xyz.avarel.kaiper.Precedence; import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.ast.Single; import xyz.avarel.kaiper.ast.flow.ConditionalExpr; import xyz.avarel.kaiper.ast.operations.BinaryOperation; import xyz.avarel.kaiper.ast.value.NullNode; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.operations.BinaryOperatorType; import xyz.avarel.kaiper.parser.BinaryParser; import xyz.avarel.kaiper.parser.KaiperParser;
/* * 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 xyz.avarel.kaiper.parser.parslets; public class ElvisParser extends BinaryParser { public ElvisParser() { super(Precedence.INFIX); } @Override public Expr parse(KaiperParser parser, Single left, Token token) { return new ConditionalExpr( token.getPosition(), new BinaryOperation( token.getPosition(), left, NullNode.VALUE,
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/flow/ConditionalExpr.java // public class ConditionalExpr extends Single { // private final Single condition; // private final Expr ifBranch; // private final Expr elseBranch; // // public ConditionalExpr(Position position, Single condition, Expr ifBranch, Expr elseBranch) { // super(position); // this.condition = condition; // this.ifBranch = ifBranch; // this.elseBranch = elseBranch; // } // // public Single getCondition() { // return condition; // } // // public Expr getIfBranch() { // return ifBranch; // } // // public Expr getElseBranch() { // return elseBranch; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public void ast(StringBuilder builder, String indent, boolean isTail) { // return if (sin(0) == 0) sin(50) else false // builder.append(indent).append(isTail ? "└── " : "├── ").append("if"); // // builder.append('\n'); // condition.ast("condition", builder, indent + (isTail ? " " : "│ "), false); // // builder.append('\n'); // ifBranch.ast("true", builder, indent + (isTail ? " " : "│ "), elseBranch == null); // // if (elseBranch != null) { // builder.append('\n'); // elseBranch.ast("false", builder, indent + (isTail ? " " : "│ "), true); // } // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/NullNode.java // public class NullNode extends Single { // public static final NullNode VALUE = new NullNode(); // // private NullNode() { // super(null); // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // } // // Path: Kaiper-Common/src/main/java/xyz/avarel/kaiper/operations/BinaryOperatorType.java // public enum BinaryOperatorType { // PLUS, // MINUS, // TIMES, // DIVIDE, // MODULUS, // POWER, // EQUALS, // NOT_EQUALS, // GREATER_THAN, // GREATER_THAN_EQUAL, // LESS_THAN, // LESS_THAN_EQUAL, // AND, // OR, // SHL, // SHR, // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/BinaryParser.java // public abstract class BinaryParser implements InfixParser { // private final int precedence; // private final boolean leftAssoc; // // public BinaryParser(int precedence) { // this(precedence, true); // } // // public BinaryParser(int precedence, boolean leftAssoc) { // this.precedence = precedence; // this.leftAssoc = leftAssoc; // } // // @Override // public Expr parse(KaiperParser parser, Expr left, Token token) { // if (!(left instanceof Single)) { // throw new SyntaxException("Internal compiler error", token.getPosition()); // } // return parse(parser, (Single) left, token); // } // // public abstract Expr parse(KaiperParser parser, Single left, Token token); // // @Override // public int getPrecedence() { // return precedence; // } // // public boolean isLeftAssoc() { // return leftAssoc; // } // } // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/ElvisParser.java import xyz.avarel.kaiper.Precedence; import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.ast.Single; import xyz.avarel.kaiper.ast.flow.ConditionalExpr; import xyz.avarel.kaiper.ast.operations.BinaryOperation; import xyz.avarel.kaiper.ast.value.NullNode; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.operations.BinaryOperatorType; import xyz.avarel.kaiper.parser.BinaryParser; import xyz.avarel.kaiper.parser.KaiperParser; /* * 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 xyz.avarel.kaiper.parser.parslets; public class ElvisParser extends BinaryParser { public ElvisParser() { super(Precedence.INFIX); } @Override public Expr parse(KaiperParser parser, Single left, Token token) { return new ConditionalExpr( token.getPosition(), new BinaryOperation( token.getPosition(), left, NullNode.VALUE,
BinaryOperatorType.EQUALS),
Avarel/Kaiper
Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/flow/ReturnParser.java
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/flow/ReturnExpr.java // public class ReturnExpr extends Single { // private final Single expr; // // public ReturnExpr(Position position, Single expr) { // super(position); // this.expr = expr; // } // // public Single getExpr() { // return expr; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public void ast(StringBuilder builder, String indent, boolean isTail) { // expr.ast("return", builder, indent, true); // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/NullNode.java // public class NullNode extends Single { // public static final NullNode VALUE = new NullNode(); // // private NullNode() { // super(null); // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/lexer/TokenType.java // public enum TokenType { // // PAIRS // LEFT_PAREN, // RIGHT_PAREN, // // LEFT_BRACKET, // RIGHT_BRACKET, // // LEFT_BRACE, // RIGHT_BRACE, // // OPTIONAL_ASSIGN, // ELVIS, // // // ASSIGNMENT // ASSIGN, // // // TYPES // INT, // NUMBER, // BOOLEAN, // FUNCTION, // STRING, // ATOM, // // // ARITHMETIC // PLUS, // MINUS, // ASTERISK, // SLASH, // BACKSLASH, // CARET, // PERCENT, // // // RELATIONAL // EQUALS, // NOT_EQUAL, // GT, // GTE, // LT, // LTE, // OR, // AND, // // // BOOLEAN // AMPERSAND, // VERTICAL_BAR, // // // MISC // REST, // RANGE_TO, // PIPE_FORWARD, // PIPE_BACKWARD, // SHIFT_RIGHT, // SHIFT_LEFT, // ARROW, // TILDE, // BANG, // QUESTION, // COLON, // COMMA, // DOT, // // UNDERSCORE, // // // SCRIPT // MODULE, // TYPE, // IDENTIFIER, // NULL, // LET, // RETURN, // IF, // ELSE, // FOR, // // LINE, // EOF, // }
import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.ast.Single; import xyz.avarel.kaiper.ast.flow.ReturnExpr; import xyz.avarel.kaiper.ast.value.NullNode; import xyz.avarel.kaiper.exceptions.SyntaxException; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.lexer.TokenType; import xyz.avarel.kaiper.parser.KaiperParser; import xyz.avarel.kaiper.parser.PrefixParser;
/* * 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 xyz.avarel.kaiper.parser.parslets.flow; public class ReturnParser implements PrefixParser { @Override public Expr parse(KaiperParser parser, Token token) { if (!parser.getParserFlags().allowControlFlows()) { throw new SyntaxException("Control flows are disabled"); } Single expr;
// Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/flow/ReturnExpr.java // public class ReturnExpr extends Single { // private final Single expr; // // public ReturnExpr(Position position, Single expr) { // super(position); // this.expr = expr; // } // // public Single getExpr() { // return expr; // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // // @Override // public void ast(StringBuilder builder, String indent, boolean isTail) { // expr.ast("return", builder, indent, true); // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/ast/value/NullNode.java // public class NullNode extends Single { // public static final NullNode VALUE = new NullNode(); // // private NullNode() { // super(null); // } // // @Override // public <R, C> R accept(ExprVisitor<R, C> visitor, C scope) { // return visitor.visit(this, scope); // } // } // // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/lexer/TokenType.java // public enum TokenType { // // PAIRS // LEFT_PAREN, // RIGHT_PAREN, // // LEFT_BRACKET, // RIGHT_BRACKET, // // LEFT_BRACE, // RIGHT_BRACE, // // OPTIONAL_ASSIGN, // ELVIS, // // // ASSIGNMENT // ASSIGN, // // // TYPES // INT, // NUMBER, // BOOLEAN, // FUNCTION, // STRING, // ATOM, // // // ARITHMETIC // PLUS, // MINUS, // ASTERISK, // SLASH, // BACKSLASH, // CARET, // PERCENT, // // // RELATIONAL // EQUALS, // NOT_EQUAL, // GT, // GTE, // LT, // LTE, // OR, // AND, // // // BOOLEAN // AMPERSAND, // VERTICAL_BAR, // // // MISC // REST, // RANGE_TO, // PIPE_FORWARD, // PIPE_BACKWARD, // SHIFT_RIGHT, // SHIFT_LEFT, // ARROW, // TILDE, // BANG, // QUESTION, // COLON, // COMMA, // DOT, // // UNDERSCORE, // // // SCRIPT // MODULE, // TYPE, // IDENTIFIER, // NULL, // LET, // RETURN, // IF, // ELSE, // FOR, // // LINE, // EOF, // } // Path: Kaiper-AST/src/main/java/xyz/avarel/kaiper/parser/parslets/flow/ReturnParser.java import xyz.avarel.kaiper.ast.Expr; import xyz.avarel.kaiper.ast.Single; import xyz.avarel.kaiper.ast.flow.ReturnExpr; import xyz.avarel.kaiper.ast.value.NullNode; import xyz.avarel.kaiper.exceptions.SyntaxException; import xyz.avarel.kaiper.lexer.Token; import xyz.avarel.kaiper.lexer.TokenType; import xyz.avarel.kaiper.parser.KaiperParser; import xyz.avarel.kaiper.parser.PrefixParser; /* * 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 xyz.avarel.kaiper.parser.parslets.flow; public class ReturnParser implements PrefixParser { @Override public Expr parse(KaiperParser parser, Token token) { if (!parser.getParserFlags().allowControlFlows()) { throw new SyntaxException("Control flows are disabled"); } Single expr;
if (parser.nextIsAny(TokenType.LINE, TokenType.RIGHT_BRACE)) {