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 |
|---|---|---|---|---|---|---|
dkharrat/NexusDialog | sample/src/main/java/com/github/dkharrat/nexusdialog/sample/CustomValidation.java | // Path: nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/InputValidator.java
// public interface InputValidator {
// /**
// * Defines the validity of an object against a specific requirement.
// *
// * @param value The input value to check.
// * @param fieldName The name of the field,
// * can be used to generate a specific error message.
// * @param fieldLabel The label of the field,
// * can be used to generate a specific error message.
// * @return ValidationError If the input does not pass the validation requirements, null otherwise.
// */
// ValidationError validate(Object value, String fieldName, String fieldLabel);
// }
//
// Path: nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/ValidationError.java
// public abstract class ValidationError {
// private final String fieldName;
// private final String fieldLabel;
//
// /**
// * Creates a new instance with the specified field name.
// *
// * @param fieldName the field name
// * @param fieldLabel the field label
// */
// public ValidationError(String fieldName, String fieldLabel) {
// this.fieldName = fieldName;
// this.fieldLabel = fieldLabel;
// }
//
// /**
// * Returns the name of the field associated with the validation error.
// *
// * @return the name of the field that has the error
// */
// public String getFieldName() {
// return fieldName;
// }
//
// /**
// * Returns the label associated to the field.
// *
// * @return the display value of the field.
// */
// public String getFieldLabel() {
// return fieldLabel;
// }
//
// /**
// * Returns a human-readable description of the validation error.
// *
// * @param resources the application's resources
// * @return a string describing the error
// */
// public abstract String getMessage(Resources resources);
// }
| import android.content.res.Resources;
import com.github.dkharrat.nexusdialog.validations.InputValidator;
import com.github.dkharrat.nexusdialog.validations.ValidationError; | package com.github.dkharrat.nexusdialog.sample;
public class CustomValidation implements InputValidator {
@Override | // Path: nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/InputValidator.java
// public interface InputValidator {
// /**
// * Defines the validity of an object against a specific requirement.
// *
// * @param value The input value to check.
// * @param fieldName The name of the field,
// * can be used to generate a specific error message.
// * @param fieldLabel The label of the field,
// * can be used to generate a specific error message.
// * @return ValidationError If the input does not pass the validation requirements, null otherwise.
// */
// ValidationError validate(Object value, String fieldName, String fieldLabel);
// }
//
// Path: nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/ValidationError.java
// public abstract class ValidationError {
// private final String fieldName;
// private final String fieldLabel;
//
// /**
// * Creates a new instance with the specified field name.
// *
// * @param fieldName the field name
// * @param fieldLabel the field label
// */
// public ValidationError(String fieldName, String fieldLabel) {
// this.fieldName = fieldName;
// this.fieldLabel = fieldLabel;
// }
//
// /**
// * Returns the name of the field associated with the validation error.
// *
// * @return the name of the field that has the error
// */
// public String getFieldName() {
// return fieldName;
// }
//
// /**
// * Returns the label associated to the field.
// *
// * @return the display value of the field.
// */
// public String getFieldLabel() {
// return fieldLabel;
// }
//
// /**
// * Returns a human-readable description of the validation error.
// *
// * @param resources the application's resources
// * @return a string describing the error
// */
// public abstract String getMessage(Resources resources);
// }
// Path: sample/src/main/java/com/github/dkharrat/nexusdialog/sample/CustomValidation.java
import android.content.res.Resources;
import com.github.dkharrat.nexusdialog.validations.InputValidator;
import com.github.dkharrat.nexusdialog.validations.ValidationError;
package com.github.dkharrat.nexusdialog.sample;
public class CustomValidation implements InputValidator {
@Override | public ValidationError validate(Object value, String fieldName, String fieldLabel) { |
sedenardi/vibevault | app/src/main/java/com/code/android/vibevault/VotesFragment.java | // Path: app/src/main/java/com/code/android/vibevault/SearchFragment.java
// public interface SearchActionListener {
// public void onShowSelected(ArchiveShowObj show);
// }
| import java.util.ArrayList;
import com.code.android.vibevault.SearchFragment.SearchActionListener;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import android.widget.Toast; | package com.code.android.vibevault;
public class VotesFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<?>>, ActionBar.OnNavigationListener {
protected static final String LOG_TAG = VotesFragment.class.getName();
private DialogAndNavigationListener dialogAndNavigationListener;
private ListView votedList;
private ArrayList<ArchiveVoteObj> votes;
protected Button moreButton;
private int offset = 0;
private int voteType = Voting.VOTES_SHOWS;
private int voteResultType = Voting.VOTES_NEWEST_VOTED;
private int numResults = 10;
private int artistId = -1;
private int currentSelectedMode = -1;
private ShareActionProvider mShareActionProvider;
private StaticDataStore db;
private boolean moreResults = false;
private VotesActionListener votesActionListener; | // Path: app/src/main/java/com/code/android/vibevault/SearchFragment.java
// public interface SearchActionListener {
// public void onShowSelected(ArchiveShowObj show);
// }
// Path: app/src/main/java/com/code/android/vibevault/VotesFragment.java
import java.util.ArrayList;
import com.code.android.vibevault.SearchFragment.SearchActionListener;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import android.widget.Toast;
package com.code.android.vibevault;
public class VotesFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<?>>, ActionBar.OnNavigationListener {
protected static final String LOG_TAG = VotesFragment.class.getName();
private DialogAndNavigationListener dialogAndNavigationListener;
private ListView votedList;
private ArrayList<ArchiveVoteObj> votes;
protected Button moreButton;
private int offset = 0;
private int voteType = Voting.VOTES_SHOWS;
private int voteResultType = Voting.VOTES_NEWEST_VOTED;
private int numResults = 10;
private int artistId = -1;
private int currentSelectedMode = -1;
private ShareActionProvider mShareActionProvider;
private StaticDataStore db;
private boolean moreResults = false;
private VotesActionListener votesActionListener; | private SearchActionListener searchActionListener; |
sedenardi/vibevault | app/src/main/java/com/code/android/vibevault/ShowsDownloadedFragment.java | // Path: app/src/main/java/com/code/android/vibevault/SearchFragment.java
// public interface SearchActionListener {
// public void onShowSelected(ArchiveShowObj show);
// }
| import java.io.File;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.code.android.vibevault.SearchFragment.SearchActionListener;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Loader;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
| package com.code.android.vibevault;
public class ShowsDownloadedFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<ArchiveShowObj>>, OnItemClickListener, ActionBar.OnNavigationListener {
private static final String LOG_TAG = ShowsDownloadedFragment.class.getName();
private DialogAndNavigationListener dialogAndNavigationListener;
private ListView downloadedList;
private StaticDataStore db;
| // Path: app/src/main/java/com/code/android/vibevault/SearchFragment.java
// public interface SearchActionListener {
// public void onShowSelected(ArchiveShowObj show);
// }
// Path: app/src/main/java/com/code/android/vibevault/ShowsDownloadedFragment.java
import java.io.File;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.code.android.vibevault.SearchFragment.SearchActionListener;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Loader;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
package com.code.android.vibevault;
public class ShowsDownloadedFragment extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<ArchiveShowObj>>, OnItemClickListener, ActionBar.OnNavigationListener {
private static final String LOG_TAG = ShowsDownloadedFragment.class.getName();
private DialogAndNavigationListener dialogAndNavigationListener;
private ListView downloadedList;
private StaticDataStore db;
| private SearchActionListener searchActionListener;
|
sedenardi/vibevault | app/src/main/java/com/code/android/vibevault/ShowsStoredFragment.java | // Path: app/src/main/java/com/code/android/vibevault/SearchFragment.java
// public interface SearchActionListener {
// public void onShowSelected(ArchiveShowObj show);
// }
| import java.util.ArrayList;
import com.code.android.vibevault.SearchFragment.SearchActionListener;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.Loader;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
| package com.code.android.vibevault;
public class ShowsStoredFragment extends Fragment implements
LoaderManager.LoaderCallbacks<ArrayList<ArchiveShowObj>>,
OnItemClickListener, ActionBar.OnNavigationListener {
private static final String LOG_TAG = ShowsStoredFragment.class.getName();
private DialogAndNavigationListener dialogAndNavigationListener;
private ListView storedList;
private StaticDataStore db;
| // Path: app/src/main/java/com/code/android/vibevault/SearchFragment.java
// public interface SearchActionListener {
// public void onShowSelected(ArchiveShowObj show);
// }
// Path: app/src/main/java/com/code/android/vibevault/ShowsStoredFragment.java
import java.util.ArrayList;
import com.code.android.vibevault.SearchFragment.SearchActionListener;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.Loader;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
package com.code.android.vibevault;
public class ShowsStoredFragment extends Fragment implements
LoaderManager.LoaderCallbacks<ArrayList<ArchiveShowObj>>,
OnItemClickListener, ActionBar.OnNavigationListener {
private static final String LOG_TAG = ShowsStoredFragment.class.getName();
private DialogAndNavigationListener dialogAndNavigationListener;
private ListView storedList;
private StaticDataStore db;
| private SearchActionListener searchActionListener;
|
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/config/audit/AuditEventConverter.java | // Path: src/main/java/org/lightadmin/jhipster/domain/PersistentAuditEvent.java
// @Entity
// @Table(name = "T_PERSISTENT_AUDIT_EVENT")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
// public class PersistentAuditEvent {
//
// @Id
// @GeneratedValue(strategy = GenerationType.TABLE)
// @Column(name = "event_id")
// private Long id;
//
// @NotNull
// private String principal;
//
// @Column(name = "event_date")
// @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
// private LocalDateTime auditEventDate;
//
// @Column(name = "event_type")
// private String auditEventType;
//
// @ElementCollection
// @MapKeyColumn(name="name")
// @Column(name="value")
// @CollectionTable(name="T_PERSISTENT_AUDIT_EVENT_DATA", joinColumns=@JoinColumn(name="event_id"))
// private Map<String, String> data = new HashMap<>();
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getPrincipal() {
// return principal;
// }
//
// public void setPrincipal(String principal) {
// this.principal = principal;
// }
//
// public LocalDateTime getAuditEventDate() {
// return auditEventDate;
// }
//
// public void setAuditEventDate(LocalDateTime auditEventDate) {
// this.auditEventDate = auditEventDate;
// }
//
// public String getAuditEventType() {
// return auditEventType;
// }
//
// public void setAuditEventType(String auditEventType) {
// this.auditEventType = auditEventType;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public void setData(Map<String, String> data) {
// this.data = data;
// }
// }
| import org.lightadmin.jhipster.domain.PersistentAuditEvent;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import java.util.*; | package org.lightadmin.jhipster.config.audit;
@Configuration
public class AuditEventConverter {
/**
* Convert a list of PersistentAuditEvent to a list of AuditEvent
* @param persistentAuditEvents the list to convert
* @return the converted list.
*/ | // Path: src/main/java/org/lightadmin/jhipster/domain/PersistentAuditEvent.java
// @Entity
// @Table(name = "T_PERSISTENT_AUDIT_EVENT")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
// public class PersistentAuditEvent {
//
// @Id
// @GeneratedValue(strategy = GenerationType.TABLE)
// @Column(name = "event_id")
// private Long id;
//
// @NotNull
// private String principal;
//
// @Column(name = "event_date")
// @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
// private LocalDateTime auditEventDate;
//
// @Column(name = "event_type")
// private String auditEventType;
//
// @ElementCollection
// @MapKeyColumn(name="name")
// @Column(name="value")
// @CollectionTable(name="T_PERSISTENT_AUDIT_EVENT_DATA", joinColumns=@JoinColumn(name="event_id"))
// private Map<String, String> data = new HashMap<>();
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getPrincipal() {
// return principal;
// }
//
// public void setPrincipal(String principal) {
// this.principal = principal;
// }
//
// public LocalDateTime getAuditEventDate() {
// return auditEventDate;
// }
//
// public void setAuditEventDate(LocalDateTime auditEventDate) {
// this.auditEventDate = auditEventDate;
// }
//
// public String getAuditEventType() {
// return auditEventType;
// }
//
// public void setAuditEventType(String auditEventType) {
// this.auditEventType = auditEventType;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public void setData(Map<String, String> data) {
// this.data = data;
// }
// }
// Path: src/main/java/org/lightadmin/jhipster/config/audit/AuditEventConverter.java
import org.lightadmin.jhipster.domain.PersistentAuditEvent;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import java.util.*;
package org.lightadmin.jhipster.config.audit;
@Configuration
public class AuditEventConverter {
/**
* Convert a list of PersistentAuditEvent to a list of AuditEvent
* @param persistentAuditEvents the list to convert
* @return the converted list.
*/ | public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) { |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/web/rest/AuditResource.java | // Path: src/main/java/org/lightadmin/jhipster/security/AuthoritiesConstants.java
// public final class AuthoritiesConstants {
//
// private AuthoritiesConstants() {
// }
//
// public static final String ADMIN = "ROLE_ADMIN";
//
// public static final String USER = "ROLE_USER";
//
// public static final String ANONYMOUS = "ROLE_ANONYMOUS";
// }
//
// Path: src/main/java/org/lightadmin/jhipster/service/AuditEventService.java
// @Service
// @Transactional
// public class AuditEventService {
//
// @Inject
// private PersistenceAuditEventRepository persistenceAuditEventRepository;
//
// @Inject
// private AuditEventConverter auditEventConverter;
//
// public List<AuditEvent> findAll() {
// return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
// }
//
// public List<AuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate) {
// final List<PersistentAuditEvent> persistentAuditEvents =
// persistenceAuditEventRepository.findByDates(fromDate, toDate);
//
// return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/web/propertyeditors/LocaleDateTimeEditor.java
// public class LocaleDateTimeEditor extends PropertyEditorSupport {
//
// private final DateTimeFormatter formatter;
//
// private final boolean allowEmpty;
//
// /**
// * Create a new LocaleDateTimeEditor instance, using the given format for
// * parsing and rendering.
// * <p/>
// * The "allowEmpty" parameter states if an empty String should be allowed
// * for parsing, i.e. get interpreted as null value. Otherwise, an
// * IllegalArgumentException gets thrown.
// *
// * @param dateFormat DateFormat to use for parsing and rendering
// * @param allowEmpty if empty strings should be allowed
// */
// public LocaleDateTimeEditor(String dateFormat, boolean allowEmpty) {
// this.formatter = DateTimeFormat.forPattern(dateFormat);
// this.allowEmpty = allowEmpty;
// }
//
// /**
// * Format the YearMonthDay as String, using the specified format.
// *
// * @return DateTime formatted string
// */
// public String getAsText() {
// Date value = (Date) getValue();
// return value != null ? new LocalDateTime(value).toString(formatter) : "";
// }
//
// /**
// * Parse the value from the given text, using the specified format.
// *
// * @param text the text to format
// * @throws IllegalArgumentException
// */
// public void setAsText( String text ) throws IllegalArgumentException {
// if ( allowEmpty && !StringUtils.hasText(text) ) {
// // Treat empty String as null value.
// setValue(null);
// } else {
// setValue(new LocalDateTime(formatter.parseDateTime(text)));
// }
// }
// }
| import org.lightadmin.jhipster.security.AuthoritiesConstants;
import org.lightadmin.jhipster.service.AuditEventService;
import org.lightadmin.jhipster.web.propertyeditors.LocaleDateTimeEditor;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import java.util.List; | package org.lightadmin.jhipster.web.rest;
/**
* REST controller for getting the audit events.
*/
@RestController
@RequestMapping("/app")
public class AuditResource {
@Inject | // Path: src/main/java/org/lightadmin/jhipster/security/AuthoritiesConstants.java
// public final class AuthoritiesConstants {
//
// private AuthoritiesConstants() {
// }
//
// public static final String ADMIN = "ROLE_ADMIN";
//
// public static final String USER = "ROLE_USER";
//
// public static final String ANONYMOUS = "ROLE_ANONYMOUS";
// }
//
// Path: src/main/java/org/lightadmin/jhipster/service/AuditEventService.java
// @Service
// @Transactional
// public class AuditEventService {
//
// @Inject
// private PersistenceAuditEventRepository persistenceAuditEventRepository;
//
// @Inject
// private AuditEventConverter auditEventConverter;
//
// public List<AuditEvent> findAll() {
// return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
// }
//
// public List<AuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate) {
// final List<PersistentAuditEvent> persistentAuditEvents =
// persistenceAuditEventRepository.findByDates(fromDate, toDate);
//
// return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/web/propertyeditors/LocaleDateTimeEditor.java
// public class LocaleDateTimeEditor extends PropertyEditorSupport {
//
// private final DateTimeFormatter formatter;
//
// private final boolean allowEmpty;
//
// /**
// * Create a new LocaleDateTimeEditor instance, using the given format for
// * parsing and rendering.
// * <p/>
// * The "allowEmpty" parameter states if an empty String should be allowed
// * for parsing, i.e. get interpreted as null value. Otherwise, an
// * IllegalArgumentException gets thrown.
// *
// * @param dateFormat DateFormat to use for parsing and rendering
// * @param allowEmpty if empty strings should be allowed
// */
// public LocaleDateTimeEditor(String dateFormat, boolean allowEmpty) {
// this.formatter = DateTimeFormat.forPattern(dateFormat);
// this.allowEmpty = allowEmpty;
// }
//
// /**
// * Format the YearMonthDay as String, using the specified format.
// *
// * @return DateTime formatted string
// */
// public String getAsText() {
// Date value = (Date) getValue();
// return value != null ? new LocalDateTime(value).toString(formatter) : "";
// }
//
// /**
// * Parse the value from the given text, using the specified format.
// *
// * @param text the text to format
// * @throws IllegalArgumentException
// */
// public void setAsText( String text ) throws IllegalArgumentException {
// if ( allowEmpty && !StringUtils.hasText(text) ) {
// // Treat empty String as null value.
// setValue(null);
// } else {
// setValue(new LocalDateTime(formatter.parseDateTime(text)));
// }
// }
// }
// Path: src/main/java/org/lightadmin/jhipster/web/rest/AuditResource.java
import org.lightadmin.jhipster.security.AuthoritiesConstants;
import org.lightadmin.jhipster.service.AuditEventService;
import org.lightadmin.jhipster.web.propertyeditors.LocaleDateTimeEditor;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import java.util.List;
package org.lightadmin.jhipster.web.rest;
/**
* REST controller for getting the audit events.
*/
@RestController
@RequestMapping("/app")
public class AuditResource {
@Inject | private AuditEventService auditEventService; |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/web/rest/AuditResource.java | // Path: src/main/java/org/lightadmin/jhipster/security/AuthoritiesConstants.java
// public final class AuthoritiesConstants {
//
// private AuthoritiesConstants() {
// }
//
// public static final String ADMIN = "ROLE_ADMIN";
//
// public static final String USER = "ROLE_USER";
//
// public static final String ANONYMOUS = "ROLE_ANONYMOUS";
// }
//
// Path: src/main/java/org/lightadmin/jhipster/service/AuditEventService.java
// @Service
// @Transactional
// public class AuditEventService {
//
// @Inject
// private PersistenceAuditEventRepository persistenceAuditEventRepository;
//
// @Inject
// private AuditEventConverter auditEventConverter;
//
// public List<AuditEvent> findAll() {
// return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
// }
//
// public List<AuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate) {
// final List<PersistentAuditEvent> persistentAuditEvents =
// persistenceAuditEventRepository.findByDates(fromDate, toDate);
//
// return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/web/propertyeditors/LocaleDateTimeEditor.java
// public class LocaleDateTimeEditor extends PropertyEditorSupport {
//
// private final DateTimeFormatter formatter;
//
// private final boolean allowEmpty;
//
// /**
// * Create a new LocaleDateTimeEditor instance, using the given format for
// * parsing and rendering.
// * <p/>
// * The "allowEmpty" parameter states if an empty String should be allowed
// * for parsing, i.e. get interpreted as null value. Otherwise, an
// * IllegalArgumentException gets thrown.
// *
// * @param dateFormat DateFormat to use for parsing and rendering
// * @param allowEmpty if empty strings should be allowed
// */
// public LocaleDateTimeEditor(String dateFormat, boolean allowEmpty) {
// this.formatter = DateTimeFormat.forPattern(dateFormat);
// this.allowEmpty = allowEmpty;
// }
//
// /**
// * Format the YearMonthDay as String, using the specified format.
// *
// * @return DateTime formatted string
// */
// public String getAsText() {
// Date value = (Date) getValue();
// return value != null ? new LocalDateTime(value).toString(formatter) : "";
// }
//
// /**
// * Parse the value from the given text, using the specified format.
// *
// * @param text the text to format
// * @throws IllegalArgumentException
// */
// public void setAsText( String text ) throws IllegalArgumentException {
// if ( allowEmpty && !StringUtils.hasText(text) ) {
// // Treat empty String as null value.
// setValue(null);
// } else {
// setValue(new LocalDateTime(formatter.parseDateTime(text)));
// }
// }
// }
| import org.lightadmin.jhipster.security.AuthoritiesConstants;
import org.lightadmin.jhipster.service.AuditEventService;
import org.lightadmin.jhipster.web.propertyeditors.LocaleDateTimeEditor;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import java.util.List; | package org.lightadmin.jhipster.web.rest;
/**
* REST controller for getting the audit events.
*/
@RestController
@RequestMapping("/app")
public class AuditResource {
@Inject
private AuditEventService auditEventService;
@InitBinder
public void initBinder(WebDataBinder binder) { | // Path: src/main/java/org/lightadmin/jhipster/security/AuthoritiesConstants.java
// public final class AuthoritiesConstants {
//
// private AuthoritiesConstants() {
// }
//
// public static final String ADMIN = "ROLE_ADMIN";
//
// public static final String USER = "ROLE_USER";
//
// public static final String ANONYMOUS = "ROLE_ANONYMOUS";
// }
//
// Path: src/main/java/org/lightadmin/jhipster/service/AuditEventService.java
// @Service
// @Transactional
// public class AuditEventService {
//
// @Inject
// private PersistenceAuditEventRepository persistenceAuditEventRepository;
//
// @Inject
// private AuditEventConverter auditEventConverter;
//
// public List<AuditEvent> findAll() {
// return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
// }
//
// public List<AuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate) {
// final List<PersistentAuditEvent> persistentAuditEvents =
// persistenceAuditEventRepository.findByDates(fromDate, toDate);
//
// return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/web/propertyeditors/LocaleDateTimeEditor.java
// public class LocaleDateTimeEditor extends PropertyEditorSupport {
//
// private final DateTimeFormatter formatter;
//
// private final boolean allowEmpty;
//
// /**
// * Create a new LocaleDateTimeEditor instance, using the given format for
// * parsing and rendering.
// * <p/>
// * The "allowEmpty" parameter states if an empty String should be allowed
// * for parsing, i.e. get interpreted as null value. Otherwise, an
// * IllegalArgumentException gets thrown.
// *
// * @param dateFormat DateFormat to use for parsing and rendering
// * @param allowEmpty if empty strings should be allowed
// */
// public LocaleDateTimeEditor(String dateFormat, boolean allowEmpty) {
// this.formatter = DateTimeFormat.forPattern(dateFormat);
// this.allowEmpty = allowEmpty;
// }
//
// /**
// * Format the YearMonthDay as String, using the specified format.
// *
// * @return DateTime formatted string
// */
// public String getAsText() {
// Date value = (Date) getValue();
// return value != null ? new LocalDateTime(value).toString(formatter) : "";
// }
//
// /**
// * Parse the value from the given text, using the specified format.
// *
// * @param text the text to format
// * @throws IllegalArgumentException
// */
// public void setAsText( String text ) throws IllegalArgumentException {
// if ( allowEmpty && !StringUtils.hasText(text) ) {
// // Treat empty String as null value.
// setValue(null);
// } else {
// setValue(new LocalDateTime(formatter.parseDateTime(text)));
// }
// }
// }
// Path: src/main/java/org/lightadmin/jhipster/web/rest/AuditResource.java
import org.lightadmin.jhipster.security.AuthoritiesConstants;
import org.lightadmin.jhipster.service.AuditEventService;
import org.lightadmin.jhipster.web.propertyeditors.LocaleDateTimeEditor;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import java.util.List;
package org.lightadmin.jhipster.web.rest;
/**
* REST controller for getting the audit events.
*/
@RestController
@RequestMapping("/app")
public class AuditResource {
@Inject
private AuditEventService auditEventService;
@InitBinder
public void initBinder(WebDataBinder binder) { | binder.registerCustomEditor(LocalDateTime.class, new LocaleDateTimeEditor("yyyy-MM-dd", false)); |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/web/rest/AuditResource.java | // Path: src/main/java/org/lightadmin/jhipster/security/AuthoritiesConstants.java
// public final class AuthoritiesConstants {
//
// private AuthoritiesConstants() {
// }
//
// public static final String ADMIN = "ROLE_ADMIN";
//
// public static final String USER = "ROLE_USER";
//
// public static final String ANONYMOUS = "ROLE_ANONYMOUS";
// }
//
// Path: src/main/java/org/lightadmin/jhipster/service/AuditEventService.java
// @Service
// @Transactional
// public class AuditEventService {
//
// @Inject
// private PersistenceAuditEventRepository persistenceAuditEventRepository;
//
// @Inject
// private AuditEventConverter auditEventConverter;
//
// public List<AuditEvent> findAll() {
// return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
// }
//
// public List<AuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate) {
// final List<PersistentAuditEvent> persistentAuditEvents =
// persistenceAuditEventRepository.findByDates(fromDate, toDate);
//
// return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/web/propertyeditors/LocaleDateTimeEditor.java
// public class LocaleDateTimeEditor extends PropertyEditorSupport {
//
// private final DateTimeFormatter formatter;
//
// private final boolean allowEmpty;
//
// /**
// * Create a new LocaleDateTimeEditor instance, using the given format for
// * parsing and rendering.
// * <p/>
// * The "allowEmpty" parameter states if an empty String should be allowed
// * for parsing, i.e. get interpreted as null value. Otherwise, an
// * IllegalArgumentException gets thrown.
// *
// * @param dateFormat DateFormat to use for parsing and rendering
// * @param allowEmpty if empty strings should be allowed
// */
// public LocaleDateTimeEditor(String dateFormat, boolean allowEmpty) {
// this.formatter = DateTimeFormat.forPattern(dateFormat);
// this.allowEmpty = allowEmpty;
// }
//
// /**
// * Format the YearMonthDay as String, using the specified format.
// *
// * @return DateTime formatted string
// */
// public String getAsText() {
// Date value = (Date) getValue();
// return value != null ? new LocalDateTime(value).toString(formatter) : "";
// }
//
// /**
// * Parse the value from the given text, using the specified format.
// *
// * @param text the text to format
// * @throws IllegalArgumentException
// */
// public void setAsText( String text ) throws IllegalArgumentException {
// if ( allowEmpty && !StringUtils.hasText(text) ) {
// // Treat empty String as null value.
// setValue(null);
// } else {
// setValue(new LocalDateTime(formatter.parseDateTime(text)));
// }
// }
// }
| import org.lightadmin.jhipster.security.AuthoritiesConstants;
import org.lightadmin.jhipster.service.AuditEventService;
import org.lightadmin.jhipster.web.propertyeditors.LocaleDateTimeEditor;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import java.util.List; | package org.lightadmin.jhipster.web.rest;
/**
* REST controller for getting the audit events.
*/
@RestController
@RequestMapping("/app")
public class AuditResource {
@Inject
private AuditEventService auditEventService;
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(LocalDateTime.class, new LocaleDateTimeEditor("yyyy-MM-dd", false));
}
@RequestMapping(value = "/rest/audits/all",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE) | // Path: src/main/java/org/lightadmin/jhipster/security/AuthoritiesConstants.java
// public final class AuthoritiesConstants {
//
// private AuthoritiesConstants() {
// }
//
// public static final String ADMIN = "ROLE_ADMIN";
//
// public static final String USER = "ROLE_USER";
//
// public static final String ANONYMOUS = "ROLE_ANONYMOUS";
// }
//
// Path: src/main/java/org/lightadmin/jhipster/service/AuditEventService.java
// @Service
// @Transactional
// public class AuditEventService {
//
// @Inject
// private PersistenceAuditEventRepository persistenceAuditEventRepository;
//
// @Inject
// private AuditEventConverter auditEventConverter;
//
// public List<AuditEvent> findAll() {
// return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
// }
//
// public List<AuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate) {
// final List<PersistentAuditEvent> persistentAuditEvents =
// persistenceAuditEventRepository.findByDates(fromDate, toDate);
//
// return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/web/propertyeditors/LocaleDateTimeEditor.java
// public class LocaleDateTimeEditor extends PropertyEditorSupport {
//
// private final DateTimeFormatter formatter;
//
// private final boolean allowEmpty;
//
// /**
// * Create a new LocaleDateTimeEditor instance, using the given format for
// * parsing and rendering.
// * <p/>
// * The "allowEmpty" parameter states if an empty String should be allowed
// * for parsing, i.e. get interpreted as null value. Otherwise, an
// * IllegalArgumentException gets thrown.
// *
// * @param dateFormat DateFormat to use for parsing and rendering
// * @param allowEmpty if empty strings should be allowed
// */
// public LocaleDateTimeEditor(String dateFormat, boolean allowEmpty) {
// this.formatter = DateTimeFormat.forPattern(dateFormat);
// this.allowEmpty = allowEmpty;
// }
//
// /**
// * Format the YearMonthDay as String, using the specified format.
// *
// * @return DateTime formatted string
// */
// public String getAsText() {
// Date value = (Date) getValue();
// return value != null ? new LocalDateTime(value).toString(formatter) : "";
// }
//
// /**
// * Parse the value from the given text, using the specified format.
// *
// * @param text the text to format
// * @throws IllegalArgumentException
// */
// public void setAsText( String text ) throws IllegalArgumentException {
// if ( allowEmpty && !StringUtils.hasText(text) ) {
// // Treat empty String as null value.
// setValue(null);
// } else {
// setValue(new LocalDateTime(formatter.parseDateTime(text)));
// }
// }
// }
// Path: src/main/java/org/lightadmin/jhipster/web/rest/AuditResource.java
import org.lightadmin.jhipster.security.AuthoritiesConstants;
import org.lightadmin.jhipster.service.AuditEventService;
import org.lightadmin.jhipster.web.propertyeditors.LocaleDateTimeEditor;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import java.util.List;
package org.lightadmin.jhipster.web.rest;
/**
* REST controller for getting the audit events.
*/
@RestController
@RequestMapping("/app")
public class AuditResource {
@Inject
private AuditEventService auditEventService;
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(LocalDateTime.class, new LocaleDateTimeEditor("yyyy-MM-dd", false));
}
@RequestMapping(value = "/rest/audits/all",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE) | @RolesAllowed(AuthoritiesConstants.ADMIN) |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/aop/logging/LoggingAspect.java | // Path: src/main/java/org/lightadmin/jhipster/config/Constants.java
// public interface Constants {
//
// public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
// public static final String SPRING_PROFILE_PRODUCTION = "prod";
// public static final String SYSTEM_ACCOUNT = "system";
//
// }
| import org.lightadmin.jhipster.config.Constants;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import javax.inject.Inject;
import java.util.Arrays; | package org.lightadmin.jhipster.aop.logging;
/**
* Aspect for logging execution of service and repository Spring components.
*/
@Aspect
public class LoggingAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Inject
private Environment env;
@Pointcut("within(org.lightadmin.jhipster.repository..*) || within(org.lightadmin.jhipster.service..*) || within(org.lightadmin.jhipster.web.rest..*)")
public void loggingPoincut() {}
@AfterThrowing(pointcut = "loggingPoincut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { | // Path: src/main/java/org/lightadmin/jhipster/config/Constants.java
// public interface Constants {
//
// public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
// public static final String SPRING_PROFILE_PRODUCTION = "prod";
// public static final String SYSTEM_ACCOUNT = "system";
//
// }
// Path: src/main/java/org/lightadmin/jhipster/aop/logging/LoggingAspect.java
import org.lightadmin.jhipster.config.Constants;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import javax.inject.Inject;
import java.util.Arrays;
package org.lightadmin.jhipster.aop.logging;
/**
* Aspect for logging execution of service and repository Spring components.
*/
@Aspect
public class LoggingAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Inject
private Environment env;
@Pointcut("within(org.lightadmin.jhipster.repository..*) || within(org.lightadmin.jhipster.service..*) || within(org.lightadmin.jhipster.web.rest..*)")
public void loggingPoincut() {}
@AfterThrowing(pointcut = "loggingPoincut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { | if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT)) { |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/ApplicationWebXml.java | // Path: src/main/java/org/lightadmin/jhipster/config/Constants.java
// public interface Constants {
//
// public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
// public static final String SPRING_PROFILE_PRODUCTION = "prod";
// public static final String SYSTEM_ACCOUNT = "system";
//
// }
| import org.lightadmin.jhipster.config.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer; | package org.lightadmin.jhipster;
/**
* This is an helper Java class that provides an alternative to creating a web.xml.
*/
public class ApplicationWebXml extends SpringBootServletInitializer {
private final Logger log = LoggerFactory.getLogger(ApplicationWebXml.class);
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.profiles(addDefaultProfile())
.showBanner(false)
.sources(Application.class);
}
/**
* Set a default profile if it has not been set.
* <p/>
* <p>
* Please use -Dspring.profiles.active=dev
* </p>
*/
private String addDefaultProfile() {
String profile = System.getProperty("spring.profiles.active");
if (profile != null) {
log.info("Running with Spring profile(s) : {}", profile);
return profile;
}
log.warn("No Spring profile configured, running with default configuration"); | // Path: src/main/java/org/lightadmin/jhipster/config/Constants.java
// public interface Constants {
//
// public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
// public static final String SPRING_PROFILE_PRODUCTION = "prod";
// public static final String SYSTEM_ACCOUNT = "system";
//
// }
// Path: src/main/java/org/lightadmin/jhipster/ApplicationWebXml.java
import org.lightadmin.jhipster.config.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
package org.lightadmin.jhipster;
/**
* This is an helper Java class that provides an alternative to creating a web.xml.
*/
public class ApplicationWebXml extends SpringBootServletInitializer {
private final Logger log = LoggerFactory.getLogger(ApplicationWebXml.class);
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.profiles(addDefaultProfile())
.showBanner(false)
.sources(Application.class);
}
/**
* Set a default profile if it has not been set.
* <p/>
* <p>
* Please use -Dspring.profiles.active=dev
* </p>
*/
private String addDefaultProfile() {
String profile = System.getProperty("spring.profiles.active");
if (profile != null) {
log.info("Running with Spring profile(s) : {}", profile);
return profile;
}
log.warn("No Spring profile configured, running with default configuration"); | return Constants.SPRING_PROFILE_DEVELOPMENT; |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/config/AsyncConfiguration.java | // Path: src/main/java/org/lightadmin/jhipster/async/ExceptionHandlingAsyncTaskExecutor.java
// public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor,
// InitializingBean, DisposableBean {
//
// private final Logger log = LoggerFactory.getLogger(ExceptionHandlingAsyncTaskExecutor.class);
//
// private final AsyncTaskExecutor executor;
//
// public ExceptionHandlingAsyncTaskExecutor(AsyncTaskExecutor executor) {
// this.executor = executor;
// }
//
// @Override
// public void execute(Runnable task) {
// executor.execute(task);
// }
//
// @Override
// public void execute(Runnable task, long startTimeout) {
// executor.execute(createWrappedRunnable(task), startTimeout);
// }
//
// private <T> Callable<T> createCallable(final Callable<T> task) {
// return new Callable<T>() {
//
// @Override
// public T call() throws Exception {
// try {
// return task.call();
// } catch (Exception e) {
// handle(e);
// throw e;
// }
// }
// };
// }
//
// private Runnable createWrappedRunnable(final Runnable task) {
// return new Runnable() {
//
// @Override
// public void run() {
// try {
// task.run();
// } catch (Exception e) {
// handle(e);
// }
// }
// };
// }
//
// protected void handle(Exception e) {
// log.error("Caught async exception", e);
// }
//
// @Override
// public Future<?> submit(Runnable task) {
// return executor.submit(createWrappedRunnable(task));
// }
//
// @Override
// public <T> Future<T> submit(Callable<T> task) {
// return executor.submit(createCallable(task));
// }
//
// @Override
// public void destroy() throws Exception {
// if (executor instanceof DisposableBean) {
// DisposableBean bean = (DisposableBean) executor;
// bean.destroy();
// }
// }
//
// @Override
// public void afterPropertiesSet() throws Exception {
// if (executor instanceof InitializingBean) {
// InitializingBean bean = (InitializingBean) executor;
// bean.afterPropertiesSet();
// }
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import org.lightadmin.jhipster.async.ExceptionHandlingAsyncTaskExecutor; | package org.lightadmin.jhipster.config;
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer, EnvironmentAware {
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
private RelaxedPropertyResolver propertyResolver;
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, "async.");
}
@Override
@Bean
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(propertyResolver.getProperty("corePoolSize", Integer.class, 2));
executor.setMaxPoolSize(propertyResolver.getProperty("maxPoolSize", Integer.class, 50));
executor.setQueueCapacity(propertyResolver.getProperty("queueCapacity", Integer.class, 10000));
executor.setThreadNamePrefix("lightadmin-jhipster-Executor-"); | // Path: src/main/java/org/lightadmin/jhipster/async/ExceptionHandlingAsyncTaskExecutor.java
// public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor,
// InitializingBean, DisposableBean {
//
// private final Logger log = LoggerFactory.getLogger(ExceptionHandlingAsyncTaskExecutor.class);
//
// private final AsyncTaskExecutor executor;
//
// public ExceptionHandlingAsyncTaskExecutor(AsyncTaskExecutor executor) {
// this.executor = executor;
// }
//
// @Override
// public void execute(Runnable task) {
// executor.execute(task);
// }
//
// @Override
// public void execute(Runnable task, long startTimeout) {
// executor.execute(createWrappedRunnable(task), startTimeout);
// }
//
// private <T> Callable<T> createCallable(final Callable<T> task) {
// return new Callable<T>() {
//
// @Override
// public T call() throws Exception {
// try {
// return task.call();
// } catch (Exception e) {
// handle(e);
// throw e;
// }
// }
// };
// }
//
// private Runnable createWrappedRunnable(final Runnable task) {
// return new Runnable() {
//
// @Override
// public void run() {
// try {
// task.run();
// } catch (Exception e) {
// handle(e);
// }
// }
// };
// }
//
// protected void handle(Exception e) {
// log.error("Caught async exception", e);
// }
//
// @Override
// public Future<?> submit(Runnable task) {
// return executor.submit(createWrappedRunnable(task));
// }
//
// @Override
// public <T> Future<T> submit(Callable<T> task) {
// return executor.submit(createCallable(task));
// }
//
// @Override
// public void destroy() throws Exception {
// if (executor instanceof DisposableBean) {
// DisposableBean bean = (DisposableBean) executor;
// bean.destroy();
// }
// }
//
// @Override
// public void afterPropertiesSet() throws Exception {
// if (executor instanceof InitializingBean) {
// InitializingBean bean = (InitializingBean) executor;
// bean.afterPropertiesSet();
// }
// }
// }
// Path: src/main/java/org/lightadmin/jhipster/config/AsyncConfiguration.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import org.lightadmin.jhipster.async.ExceptionHandlingAsyncTaskExecutor;
package org.lightadmin.jhipster.config;
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer, EnvironmentAware {
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
private RelaxedPropertyResolver propertyResolver;
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, "async.");
}
@Override
@Bean
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(propertyResolver.getProperty("corePoolSize", Integer.class, 2));
executor.setMaxPoolSize(propertyResolver.getProperty("maxPoolSize", Integer.class, 50));
executor.setQueueCapacity(propertyResolver.getProperty("queueCapacity", Integer.class, 10000));
executor.setThreadNamePrefix("lightadmin-jhipster-Executor-"); | return new ExceptionHandlingAsyncTaskExecutor(executor); |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/web/rest/LogsResource.java | // Path: src/main/java/org/lightadmin/jhipster/web/rest/dto/LoggerDTO.java
// public class LoggerDTO {
//
// private String name;
//
// private String level;
//
// public LoggerDTO(Logger logger) {
// this.name = logger.getName();
// this.level = logger.getEffectiveLevel().toString();
// }
//
// @JsonCreator
// public LoggerDTO() {
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getLevel() {
// return level;
// }
//
// public void setLevel(String level) {
// this.level = level;
// }
//
// @Override
// public String toString() {
// return "LoggerDTO{" +
// "name='" + name + '\'' +
// ", level='" + level + '\'' +
// '}';
// }
// }
| import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.codahale.metrics.annotation.Timed;
import org.lightadmin.jhipster.web.rest.dto.LoggerDTO;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List; | package org.lightadmin.jhipster.web.rest;
/**
* Controller for view and managing Log Level at runtime.
*/
@RestController
@RequestMapping("/app")
public class LogsResource {
@RequestMapping(value = "/rest/logs",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed | // Path: src/main/java/org/lightadmin/jhipster/web/rest/dto/LoggerDTO.java
// public class LoggerDTO {
//
// private String name;
//
// private String level;
//
// public LoggerDTO(Logger logger) {
// this.name = logger.getName();
// this.level = logger.getEffectiveLevel().toString();
// }
//
// @JsonCreator
// public LoggerDTO() {
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getLevel() {
// return level;
// }
//
// public void setLevel(String level) {
// this.level = level;
// }
//
// @Override
// public String toString() {
// return "LoggerDTO{" +
// "name='" + name + '\'' +
// ", level='" + level + '\'' +
// '}';
// }
// }
// Path: src/main/java/org/lightadmin/jhipster/web/rest/LogsResource.java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.codahale.metrics.annotation.Timed;
import org.lightadmin.jhipster.web.rest.dto.LoggerDTO;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
package org.lightadmin.jhipster.web.rest;
/**
* Controller for view and managing Log Level at runtime.
*/
@RestController
@RequestMapping("/app")
public class LogsResource {
@RequestMapping(value = "/rest/logs",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed | public List<LoggerDTO> getList() { |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/config/LoggingAspectConfiguration.java | // Path: src/main/java/org/lightadmin/jhipster/aop/logging/LoggingAspect.java
// @Aspect
// public class LoggingAspect {
//
// private final Logger log = LoggerFactory.getLogger(this.getClass());
//
// @Inject
// private Environment env;
//
// @Pointcut("within(org.lightadmin.jhipster.repository..*) || within(org.lightadmin.jhipster.service..*) || within(org.lightadmin.jhipster.web.rest..*)")
// public void loggingPoincut() {}
//
// @AfterThrowing(pointcut = "loggingPoincut()", throwing = "e")
// public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
// if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT)) {
// log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
// joinPoint.getSignature().getName(), e.getCause(), e);
// } else {
// log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
// joinPoint.getSignature().getName(), e.getCause());
// }
// }
//
// @Around("loggingPoincut()")
// public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
// log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
// joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
//
// try {
// Object result = joinPoint.proceed();
// log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
// joinPoint.getSignature().getName(), result);
//
// return result;
// } catch (IllegalArgumentException e) {
// log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
// joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
//
// throw e;
// }
// }
// }
| import org.lightadmin.jhipster.aop.logging.LoggingAspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Profile; | package org.lightadmin.jhipster.config;
@Configuration
@EnableAspectJAutoProxy
public class LoggingAspectConfiguration {
@Bean
@Profile(Constants.SPRING_PROFILE_DEVELOPMENT) | // Path: src/main/java/org/lightadmin/jhipster/aop/logging/LoggingAspect.java
// @Aspect
// public class LoggingAspect {
//
// private final Logger log = LoggerFactory.getLogger(this.getClass());
//
// @Inject
// private Environment env;
//
// @Pointcut("within(org.lightadmin.jhipster.repository..*) || within(org.lightadmin.jhipster.service..*) || within(org.lightadmin.jhipster.web.rest..*)")
// public void loggingPoincut() {}
//
// @AfterThrowing(pointcut = "loggingPoincut()", throwing = "e")
// public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
// if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT)) {
// log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
// joinPoint.getSignature().getName(), e.getCause(), e);
// } else {
// log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
// joinPoint.getSignature().getName(), e.getCause());
// }
// }
//
// @Around("loggingPoincut()")
// public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
// log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
// joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
//
// try {
// Object result = joinPoint.proceed();
// log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
// joinPoint.getSignature().getName(), result);
//
// return result;
// } catch (IllegalArgumentException e) {
// log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
// joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
//
// throw e;
// }
// }
// }
// Path: src/main/java/org/lightadmin/jhipster/config/LoggingAspectConfiguration.java
import org.lightadmin.jhipster.aop.logging.LoggingAspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Profile;
package org.lightadmin.jhipster.config;
@Configuration
@EnableAspectJAutoProxy
public class LoggingAspectConfiguration {
@Bean
@Profile(Constants.SPRING_PROFILE_DEVELOPMENT) | public LoggingAspect loggingAspect() { |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/Application.java | // Path: src/main/java/org/lightadmin/jhipster/config/Constants.java
// public interface Constants {
//
// public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
// public static final String SPRING_PROFILE_PRODUCTION = "prod";
// public static final String SYSTEM_ACCOUNT = "system";
//
// }
| import org.lightadmin.jhipster.config.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.MetricRepositoryAutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
import org.springframework.core.env.SimpleCommandLinePropertySource;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.IOException;
import java.util.Arrays; | package org.lightadmin.jhipster;
@ComponentScan
@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})
public class Application {
private final Logger log = LoggerFactory.getLogger(Application.class);
@Inject
private Environment env;
/**
* Initializes lightadmin-jhipster.
* <p/>
* Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile
* <p/>
*/
@PostConstruct
public void initApplication() throws IOException {
if (env.getActiveProfiles().length == 0) {
log.warn("No Spring profile configured, running with default configuration");
} else {
log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
}
}
/**
* Main method, used to run the application.
*
* To run the application with hot reload enabled, add the following arguments to your JVM:
* "-javaagent:spring_loaded/springloaded-jhipster.jar -noverify -Dspringloaded=plugins=io.github.jhipster.loaded.instrument.JHipsterLoadtimeInstrumentationPlugin"
*/
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(false);
SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
// Check if the selected profile has been set as argument.
// if not the development profile will be added
addDefaultProfile(app, source);
app.run(args);
}
/**
* Set a default profile if it has not been set
*/
private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
if (!source.containsProperty("spring.profiles.active")) { | // Path: src/main/java/org/lightadmin/jhipster/config/Constants.java
// public interface Constants {
//
// public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
// public static final String SPRING_PROFILE_PRODUCTION = "prod";
// public static final String SYSTEM_ACCOUNT = "system";
//
// }
// Path: src/main/java/org/lightadmin/jhipster/Application.java
import org.lightadmin.jhipster.config.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.MetricRepositoryAutoConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
import org.springframework.core.env.SimpleCommandLinePropertySource;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.IOException;
import java.util.Arrays;
package org.lightadmin.jhipster;
@ComponentScan
@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})
public class Application {
private final Logger log = LoggerFactory.getLogger(Application.class);
@Inject
private Environment env;
/**
* Initializes lightadmin-jhipster.
* <p/>
* Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile
* <p/>
*/
@PostConstruct
public void initApplication() throws IOException {
if (env.getActiveProfiles().length == 0) {
log.warn("No Spring profile configured, running with default configuration");
} else {
log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
}
}
/**
* Main method, used to run the application.
*
* To run the application with hot reload enabled, add the following arguments to your JVM:
* "-javaagent:spring_loaded/springloaded-jhipster.jar -noverify -Dspringloaded=plugins=io.github.jhipster.loaded.instrument.JHipsterLoadtimeInstrumentationPlugin"
*/
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(false);
SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
// Check if the selected profile has been set as argument.
// if not the development profile will be added
addDefaultProfile(app, source);
app.run(args);
}
/**
* Set a default profile if it has not been set
*/
private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
if (!source.containsProperty("spring.profiles.active")) { | app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT); |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/repository/CustomAuditEventRepository.java | // Path: src/main/java/org/lightadmin/jhipster/config/audit/AuditEventConverter.java
// @Configuration
// public class AuditEventConverter {
//
// /**
// * Convert a list of PersistentAuditEvent to a list of AuditEvent
// * @param persistentAuditEvents the list to convert
// * @return the converted list.
// */
// public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
// if (persistentAuditEvents == null) {
// return Collections.emptyList();
// }
//
// List<AuditEvent> auditEvents = new ArrayList<>();
//
// for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
// AuditEvent auditEvent = new AuditEvent(persistentAuditEvent.getAuditEventDate().toDate(), persistentAuditEvent.getPrincipal(),
// persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
// auditEvents.add(auditEvent);
// }
//
// return auditEvents;
// }
//
// /**
// * Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
// *
// * @param data the data to convert
// * @return a map of String, Object
// */
// public Map<String, Object> convertDataToObjects(Map<String, String> data) {
// Map<String, Object> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// results.put(key, data.get(key));
// }
// }
//
// return results;
// }
//
// /**
// * Internal conversion. This method will allow to save additionnals data.
// * By default, it will save the object as string
// *
// * @param data the data to convert
// * @return a map of String, String
// */
// public Map<String, String> convertDataToStrings(Map<String, Object> data) {
// Map<String, String> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// Object object = data.get(key);
//
// // Extract the data that will be saved.
// if (object instanceof WebAuthenticationDetails) {
// WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) object;
// results.put("remoteAddress", authenticationDetails.getRemoteAddress());
// results.put("sessionId", authenticationDetails.getSessionId());
// } else {
// results.put(key, object.toString());
// }
// }
// }
//
// return results;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/domain/PersistentAuditEvent.java
// @Entity
// @Table(name = "T_PERSISTENT_AUDIT_EVENT")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
// public class PersistentAuditEvent {
//
// @Id
// @GeneratedValue(strategy = GenerationType.TABLE)
// @Column(name = "event_id")
// private Long id;
//
// @NotNull
// private String principal;
//
// @Column(name = "event_date")
// @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
// private LocalDateTime auditEventDate;
//
// @Column(name = "event_type")
// private String auditEventType;
//
// @ElementCollection
// @MapKeyColumn(name="name")
// @Column(name="value")
// @CollectionTable(name="T_PERSISTENT_AUDIT_EVENT_DATA", joinColumns=@JoinColumn(name="event_id"))
// private Map<String, String> data = new HashMap<>();
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getPrincipal() {
// return principal;
// }
//
// public void setPrincipal(String principal) {
// this.principal = principal;
// }
//
// public LocalDateTime getAuditEventDate() {
// return auditEventDate;
// }
//
// public void setAuditEventDate(LocalDateTime auditEventDate) {
// this.auditEventDate = auditEventDate;
// }
//
// public String getAuditEventType() {
// return auditEventType;
// }
//
// public void setAuditEventType(String auditEventType) {
// this.auditEventType = auditEventType;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public void setData(Map<String, String> data) {
// this.data = data;
// }
// }
| import org.lightadmin.jhipster.config.audit.AuditEventConverter;
import org.lightadmin.jhipster.domain.PersistentAuditEvent;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.actuate.audit.AuditEventRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import javax.inject.Inject;
import java.util.Date;
import java.util.List; | package org.lightadmin.jhipster.repository;
/**
* Wraps an implementation of Spring Boot's AuditEventRepository.
*/
@Repository
public class CustomAuditEventRepository {
@Inject
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Bean
public AuditEventRepository auditEventRepository() {
return new AuditEventRepository() {
@Inject | // Path: src/main/java/org/lightadmin/jhipster/config/audit/AuditEventConverter.java
// @Configuration
// public class AuditEventConverter {
//
// /**
// * Convert a list of PersistentAuditEvent to a list of AuditEvent
// * @param persistentAuditEvents the list to convert
// * @return the converted list.
// */
// public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
// if (persistentAuditEvents == null) {
// return Collections.emptyList();
// }
//
// List<AuditEvent> auditEvents = new ArrayList<>();
//
// for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
// AuditEvent auditEvent = new AuditEvent(persistentAuditEvent.getAuditEventDate().toDate(), persistentAuditEvent.getPrincipal(),
// persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
// auditEvents.add(auditEvent);
// }
//
// return auditEvents;
// }
//
// /**
// * Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
// *
// * @param data the data to convert
// * @return a map of String, Object
// */
// public Map<String, Object> convertDataToObjects(Map<String, String> data) {
// Map<String, Object> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// results.put(key, data.get(key));
// }
// }
//
// return results;
// }
//
// /**
// * Internal conversion. This method will allow to save additionnals data.
// * By default, it will save the object as string
// *
// * @param data the data to convert
// * @return a map of String, String
// */
// public Map<String, String> convertDataToStrings(Map<String, Object> data) {
// Map<String, String> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// Object object = data.get(key);
//
// // Extract the data that will be saved.
// if (object instanceof WebAuthenticationDetails) {
// WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) object;
// results.put("remoteAddress", authenticationDetails.getRemoteAddress());
// results.put("sessionId", authenticationDetails.getSessionId());
// } else {
// results.put(key, object.toString());
// }
// }
// }
//
// return results;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/domain/PersistentAuditEvent.java
// @Entity
// @Table(name = "T_PERSISTENT_AUDIT_EVENT")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
// public class PersistentAuditEvent {
//
// @Id
// @GeneratedValue(strategy = GenerationType.TABLE)
// @Column(name = "event_id")
// private Long id;
//
// @NotNull
// private String principal;
//
// @Column(name = "event_date")
// @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
// private LocalDateTime auditEventDate;
//
// @Column(name = "event_type")
// private String auditEventType;
//
// @ElementCollection
// @MapKeyColumn(name="name")
// @Column(name="value")
// @CollectionTable(name="T_PERSISTENT_AUDIT_EVENT_DATA", joinColumns=@JoinColumn(name="event_id"))
// private Map<String, String> data = new HashMap<>();
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getPrincipal() {
// return principal;
// }
//
// public void setPrincipal(String principal) {
// this.principal = principal;
// }
//
// public LocalDateTime getAuditEventDate() {
// return auditEventDate;
// }
//
// public void setAuditEventDate(LocalDateTime auditEventDate) {
// this.auditEventDate = auditEventDate;
// }
//
// public String getAuditEventType() {
// return auditEventType;
// }
//
// public void setAuditEventType(String auditEventType) {
// this.auditEventType = auditEventType;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public void setData(Map<String, String> data) {
// this.data = data;
// }
// }
// Path: src/main/java/org/lightadmin/jhipster/repository/CustomAuditEventRepository.java
import org.lightadmin.jhipster.config.audit.AuditEventConverter;
import org.lightadmin.jhipster.domain.PersistentAuditEvent;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.actuate.audit.AuditEventRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import javax.inject.Inject;
import java.util.Date;
import java.util.List;
package org.lightadmin.jhipster.repository;
/**
* Wraps an implementation of Spring Boot's AuditEventRepository.
*/
@Repository
public class CustomAuditEventRepository {
@Inject
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Bean
public AuditEventRepository auditEventRepository() {
return new AuditEventRepository() {
@Inject | private AuditEventConverter auditEventConverter; |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/repository/CustomAuditEventRepository.java | // Path: src/main/java/org/lightadmin/jhipster/config/audit/AuditEventConverter.java
// @Configuration
// public class AuditEventConverter {
//
// /**
// * Convert a list of PersistentAuditEvent to a list of AuditEvent
// * @param persistentAuditEvents the list to convert
// * @return the converted list.
// */
// public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
// if (persistentAuditEvents == null) {
// return Collections.emptyList();
// }
//
// List<AuditEvent> auditEvents = new ArrayList<>();
//
// for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
// AuditEvent auditEvent = new AuditEvent(persistentAuditEvent.getAuditEventDate().toDate(), persistentAuditEvent.getPrincipal(),
// persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
// auditEvents.add(auditEvent);
// }
//
// return auditEvents;
// }
//
// /**
// * Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
// *
// * @param data the data to convert
// * @return a map of String, Object
// */
// public Map<String, Object> convertDataToObjects(Map<String, String> data) {
// Map<String, Object> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// results.put(key, data.get(key));
// }
// }
//
// return results;
// }
//
// /**
// * Internal conversion. This method will allow to save additionnals data.
// * By default, it will save the object as string
// *
// * @param data the data to convert
// * @return a map of String, String
// */
// public Map<String, String> convertDataToStrings(Map<String, Object> data) {
// Map<String, String> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// Object object = data.get(key);
//
// // Extract the data that will be saved.
// if (object instanceof WebAuthenticationDetails) {
// WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) object;
// results.put("remoteAddress", authenticationDetails.getRemoteAddress());
// results.put("sessionId", authenticationDetails.getSessionId());
// } else {
// results.put(key, object.toString());
// }
// }
// }
//
// return results;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/domain/PersistentAuditEvent.java
// @Entity
// @Table(name = "T_PERSISTENT_AUDIT_EVENT")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
// public class PersistentAuditEvent {
//
// @Id
// @GeneratedValue(strategy = GenerationType.TABLE)
// @Column(name = "event_id")
// private Long id;
//
// @NotNull
// private String principal;
//
// @Column(name = "event_date")
// @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
// private LocalDateTime auditEventDate;
//
// @Column(name = "event_type")
// private String auditEventType;
//
// @ElementCollection
// @MapKeyColumn(name="name")
// @Column(name="value")
// @CollectionTable(name="T_PERSISTENT_AUDIT_EVENT_DATA", joinColumns=@JoinColumn(name="event_id"))
// private Map<String, String> data = new HashMap<>();
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getPrincipal() {
// return principal;
// }
//
// public void setPrincipal(String principal) {
// this.principal = principal;
// }
//
// public LocalDateTime getAuditEventDate() {
// return auditEventDate;
// }
//
// public void setAuditEventDate(LocalDateTime auditEventDate) {
// this.auditEventDate = auditEventDate;
// }
//
// public String getAuditEventType() {
// return auditEventType;
// }
//
// public void setAuditEventType(String auditEventType) {
// this.auditEventType = auditEventType;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public void setData(Map<String, String> data) {
// this.data = data;
// }
// }
| import org.lightadmin.jhipster.config.audit.AuditEventConverter;
import org.lightadmin.jhipster.domain.PersistentAuditEvent;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.actuate.audit.AuditEventRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import javax.inject.Inject;
import java.util.Date;
import java.util.List; | package org.lightadmin.jhipster.repository;
/**
* Wraps an implementation of Spring Boot's AuditEventRepository.
*/
@Repository
public class CustomAuditEventRepository {
@Inject
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Bean
public AuditEventRepository auditEventRepository() {
return new AuditEventRepository() {
@Inject
private AuditEventConverter auditEventConverter;
@Override
public List<AuditEvent> find(String principal, Date after) { | // Path: src/main/java/org/lightadmin/jhipster/config/audit/AuditEventConverter.java
// @Configuration
// public class AuditEventConverter {
//
// /**
// * Convert a list of PersistentAuditEvent to a list of AuditEvent
// * @param persistentAuditEvents the list to convert
// * @return the converted list.
// */
// public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
// if (persistentAuditEvents == null) {
// return Collections.emptyList();
// }
//
// List<AuditEvent> auditEvents = new ArrayList<>();
//
// for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
// AuditEvent auditEvent = new AuditEvent(persistentAuditEvent.getAuditEventDate().toDate(), persistentAuditEvent.getPrincipal(),
// persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
// auditEvents.add(auditEvent);
// }
//
// return auditEvents;
// }
//
// /**
// * Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
// *
// * @param data the data to convert
// * @return a map of String, Object
// */
// public Map<String, Object> convertDataToObjects(Map<String, String> data) {
// Map<String, Object> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// results.put(key, data.get(key));
// }
// }
//
// return results;
// }
//
// /**
// * Internal conversion. This method will allow to save additionnals data.
// * By default, it will save the object as string
// *
// * @param data the data to convert
// * @return a map of String, String
// */
// public Map<String, String> convertDataToStrings(Map<String, Object> data) {
// Map<String, String> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// Object object = data.get(key);
//
// // Extract the data that will be saved.
// if (object instanceof WebAuthenticationDetails) {
// WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) object;
// results.put("remoteAddress", authenticationDetails.getRemoteAddress());
// results.put("sessionId", authenticationDetails.getSessionId());
// } else {
// results.put(key, object.toString());
// }
// }
// }
//
// return results;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/domain/PersistentAuditEvent.java
// @Entity
// @Table(name = "T_PERSISTENT_AUDIT_EVENT")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
// public class PersistentAuditEvent {
//
// @Id
// @GeneratedValue(strategy = GenerationType.TABLE)
// @Column(name = "event_id")
// private Long id;
//
// @NotNull
// private String principal;
//
// @Column(name = "event_date")
// @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
// private LocalDateTime auditEventDate;
//
// @Column(name = "event_type")
// private String auditEventType;
//
// @ElementCollection
// @MapKeyColumn(name="name")
// @Column(name="value")
// @CollectionTable(name="T_PERSISTENT_AUDIT_EVENT_DATA", joinColumns=@JoinColumn(name="event_id"))
// private Map<String, String> data = new HashMap<>();
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getPrincipal() {
// return principal;
// }
//
// public void setPrincipal(String principal) {
// this.principal = principal;
// }
//
// public LocalDateTime getAuditEventDate() {
// return auditEventDate;
// }
//
// public void setAuditEventDate(LocalDateTime auditEventDate) {
// this.auditEventDate = auditEventDate;
// }
//
// public String getAuditEventType() {
// return auditEventType;
// }
//
// public void setAuditEventType(String auditEventType) {
// this.auditEventType = auditEventType;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public void setData(Map<String, String> data) {
// this.data = data;
// }
// }
// Path: src/main/java/org/lightadmin/jhipster/repository/CustomAuditEventRepository.java
import org.lightadmin.jhipster.config.audit.AuditEventConverter;
import org.lightadmin.jhipster.domain.PersistentAuditEvent;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.actuate.audit.AuditEventRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import javax.inject.Inject;
import java.util.Date;
import java.util.List;
package org.lightadmin.jhipster.repository;
/**
* Wraps an implementation of Spring Boot's AuditEventRepository.
*/
@Repository
public class CustomAuditEventRepository {
@Inject
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Bean
public AuditEventRepository auditEventRepository() {
return new AuditEventRepository() {
@Inject
private AuditEventConverter auditEventConverter;
@Override
public List<AuditEvent> find(String principal, Date after) { | final Iterable<PersistentAuditEvent> persistentAuditEvents; |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/service/AuditEventService.java | // Path: src/main/java/org/lightadmin/jhipster/config/audit/AuditEventConverter.java
// @Configuration
// public class AuditEventConverter {
//
// /**
// * Convert a list of PersistentAuditEvent to a list of AuditEvent
// * @param persistentAuditEvents the list to convert
// * @return the converted list.
// */
// public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
// if (persistentAuditEvents == null) {
// return Collections.emptyList();
// }
//
// List<AuditEvent> auditEvents = new ArrayList<>();
//
// for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
// AuditEvent auditEvent = new AuditEvent(persistentAuditEvent.getAuditEventDate().toDate(), persistentAuditEvent.getPrincipal(),
// persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
// auditEvents.add(auditEvent);
// }
//
// return auditEvents;
// }
//
// /**
// * Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
// *
// * @param data the data to convert
// * @return a map of String, Object
// */
// public Map<String, Object> convertDataToObjects(Map<String, String> data) {
// Map<String, Object> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// results.put(key, data.get(key));
// }
// }
//
// return results;
// }
//
// /**
// * Internal conversion. This method will allow to save additionnals data.
// * By default, it will save the object as string
// *
// * @param data the data to convert
// * @return a map of String, String
// */
// public Map<String, String> convertDataToStrings(Map<String, Object> data) {
// Map<String, String> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// Object object = data.get(key);
//
// // Extract the data that will be saved.
// if (object instanceof WebAuthenticationDetails) {
// WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) object;
// results.put("remoteAddress", authenticationDetails.getRemoteAddress());
// results.put("sessionId", authenticationDetails.getSessionId());
// } else {
// results.put(key, object.toString());
// }
// }
// }
//
// return results;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/domain/PersistentAuditEvent.java
// @Entity
// @Table(name = "T_PERSISTENT_AUDIT_EVENT")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
// public class PersistentAuditEvent {
//
// @Id
// @GeneratedValue(strategy = GenerationType.TABLE)
// @Column(name = "event_id")
// private Long id;
//
// @NotNull
// private String principal;
//
// @Column(name = "event_date")
// @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
// private LocalDateTime auditEventDate;
//
// @Column(name = "event_type")
// private String auditEventType;
//
// @ElementCollection
// @MapKeyColumn(name="name")
// @Column(name="value")
// @CollectionTable(name="T_PERSISTENT_AUDIT_EVENT_DATA", joinColumns=@JoinColumn(name="event_id"))
// private Map<String, String> data = new HashMap<>();
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getPrincipal() {
// return principal;
// }
//
// public void setPrincipal(String principal) {
// this.principal = principal;
// }
//
// public LocalDateTime getAuditEventDate() {
// return auditEventDate;
// }
//
// public void setAuditEventDate(LocalDateTime auditEventDate) {
// this.auditEventDate = auditEventDate;
// }
//
// public String getAuditEventType() {
// return auditEventType;
// }
//
// public void setAuditEventType(String auditEventType) {
// this.auditEventType = auditEventType;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public void setData(Map<String, String> data) {
// this.data = data;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/repository/PersistenceAuditEventRepository.java
// public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, String> {
//
// List<PersistentAuditEvent> findByPrincipal(String principal);
//
// List<PersistentAuditEvent> findByPrincipalAndAuditEventDateGreaterThan(String principal, LocalDateTime after);
//
// @Query("select p from PersistentAuditEvent p where p.auditEventDate >= ?1 and p.auditEventDate <= ?2")
// List<PersistentAuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate);
// }
| import org.lightadmin.jhipster.config.audit.AuditEventConverter;
import org.lightadmin.jhipster.domain.PersistentAuditEvent;
import org.lightadmin.jhipster.repository.PersistenceAuditEventRepository;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List; | package org.lightadmin.jhipster.service;
/**
* Service for managing audit events.
* <p/>
* <p>
* This is the default implementation to support SpringBoot Actuator AuditEventRepository
* </p>
*/
@Service
@Transactional
public class AuditEventService {
@Inject | // Path: src/main/java/org/lightadmin/jhipster/config/audit/AuditEventConverter.java
// @Configuration
// public class AuditEventConverter {
//
// /**
// * Convert a list of PersistentAuditEvent to a list of AuditEvent
// * @param persistentAuditEvents the list to convert
// * @return the converted list.
// */
// public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
// if (persistentAuditEvents == null) {
// return Collections.emptyList();
// }
//
// List<AuditEvent> auditEvents = new ArrayList<>();
//
// for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
// AuditEvent auditEvent = new AuditEvent(persistentAuditEvent.getAuditEventDate().toDate(), persistentAuditEvent.getPrincipal(),
// persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
// auditEvents.add(auditEvent);
// }
//
// return auditEvents;
// }
//
// /**
// * Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
// *
// * @param data the data to convert
// * @return a map of String, Object
// */
// public Map<String, Object> convertDataToObjects(Map<String, String> data) {
// Map<String, Object> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// results.put(key, data.get(key));
// }
// }
//
// return results;
// }
//
// /**
// * Internal conversion. This method will allow to save additionnals data.
// * By default, it will save the object as string
// *
// * @param data the data to convert
// * @return a map of String, String
// */
// public Map<String, String> convertDataToStrings(Map<String, Object> data) {
// Map<String, String> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// Object object = data.get(key);
//
// // Extract the data that will be saved.
// if (object instanceof WebAuthenticationDetails) {
// WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) object;
// results.put("remoteAddress", authenticationDetails.getRemoteAddress());
// results.put("sessionId", authenticationDetails.getSessionId());
// } else {
// results.put(key, object.toString());
// }
// }
// }
//
// return results;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/domain/PersistentAuditEvent.java
// @Entity
// @Table(name = "T_PERSISTENT_AUDIT_EVENT")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
// public class PersistentAuditEvent {
//
// @Id
// @GeneratedValue(strategy = GenerationType.TABLE)
// @Column(name = "event_id")
// private Long id;
//
// @NotNull
// private String principal;
//
// @Column(name = "event_date")
// @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
// private LocalDateTime auditEventDate;
//
// @Column(name = "event_type")
// private String auditEventType;
//
// @ElementCollection
// @MapKeyColumn(name="name")
// @Column(name="value")
// @CollectionTable(name="T_PERSISTENT_AUDIT_EVENT_DATA", joinColumns=@JoinColumn(name="event_id"))
// private Map<String, String> data = new HashMap<>();
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getPrincipal() {
// return principal;
// }
//
// public void setPrincipal(String principal) {
// this.principal = principal;
// }
//
// public LocalDateTime getAuditEventDate() {
// return auditEventDate;
// }
//
// public void setAuditEventDate(LocalDateTime auditEventDate) {
// this.auditEventDate = auditEventDate;
// }
//
// public String getAuditEventType() {
// return auditEventType;
// }
//
// public void setAuditEventType(String auditEventType) {
// this.auditEventType = auditEventType;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public void setData(Map<String, String> data) {
// this.data = data;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/repository/PersistenceAuditEventRepository.java
// public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, String> {
//
// List<PersistentAuditEvent> findByPrincipal(String principal);
//
// List<PersistentAuditEvent> findByPrincipalAndAuditEventDateGreaterThan(String principal, LocalDateTime after);
//
// @Query("select p from PersistentAuditEvent p where p.auditEventDate >= ?1 and p.auditEventDate <= ?2")
// List<PersistentAuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate);
// }
// Path: src/main/java/org/lightadmin/jhipster/service/AuditEventService.java
import org.lightadmin.jhipster.config.audit.AuditEventConverter;
import org.lightadmin.jhipster.domain.PersistentAuditEvent;
import org.lightadmin.jhipster.repository.PersistenceAuditEventRepository;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List;
package org.lightadmin.jhipster.service;
/**
* Service for managing audit events.
* <p/>
* <p>
* This is the default implementation to support SpringBoot Actuator AuditEventRepository
* </p>
*/
@Service
@Transactional
public class AuditEventService {
@Inject | private PersistenceAuditEventRepository persistenceAuditEventRepository; |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/service/AuditEventService.java | // Path: src/main/java/org/lightadmin/jhipster/config/audit/AuditEventConverter.java
// @Configuration
// public class AuditEventConverter {
//
// /**
// * Convert a list of PersistentAuditEvent to a list of AuditEvent
// * @param persistentAuditEvents the list to convert
// * @return the converted list.
// */
// public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
// if (persistentAuditEvents == null) {
// return Collections.emptyList();
// }
//
// List<AuditEvent> auditEvents = new ArrayList<>();
//
// for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
// AuditEvent auditEvent = new AuditEvent(persistentAuditEvent.getAuditEventDate().toDate(), persistentAuditEvent.getPrincipal(),
// persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
// auditEvents.add(auditEvent);
// }
//
// return auditEvents;
// }
//
// /**
// * Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
// *
// * @param data the data to convert
// * @return a map of String, Object
// */
// public Map<String, Object> convertDataToObjects(Map<String, String> data) {
// Map<String, Object> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// results.put(key, data.get(key));
// }
// }
//
// return results;
// }
//
// /**
// * Internal conversion. This method will allow to save additionnals data.
// * By default, it will save the object as string
// *
// * @param data the data to convert
// * @return a map of String, String
// */
// public Map<String, String> convertDataToStrings(Map<String, Object> data) {
// Map<String, String> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// Object object = data.get(key);
//
// // Extract the data that will be saved.
// if (object instanceof WebAuthenticationDetails) {
// WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) object;
// results.put("remoteAddress", authenticationDetails.getRemoteAddress());
// results.put("sessionId", authenticationDetails.getSessionId());
// } else {
// results.put(key, object.toString());
// }
// }
// }
//
// return results;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/domain/PersistentAuditEvent.java
// @Entity
// @Table(name = "T_PERSISTENT_AUDIT_EVENT")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
// public class PersistentAuditEvent {
//
// @Id
// @GeneratedValue(strategy = GenerationType.TABLE)
// @Column(name = "event_id")
// private Long id;
//
// @NotNull
// private String principal;
//
// @Column(name = "event_date")
// @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
// private LocalDateTime auditEventDate;
//
// @Column(name = "event_type")
// private String auditEventType;
//
// @ElementCollection
// @MapKeyColumn(name="name")
// @Column(name="value")
// @CollectionTable(name="T_PERSISTENT_AUDIT_EVENT_DATA", joinColumns=@JoinColumn(name="event_id"))
// private Map<String, String> data = new HashMap<>();
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getPrincipal() {
// return principal;
// }
//
// public void setPrincipal(String principal) {
// this.principal = principal;
// }
//
// public LocalDateTime getAuditEventDate() {
// return auditEventDate;
// }
//
// public void setAuditEventDate(LocalDateTime auditEventDate) {
// this.auditEventDate = auditEventDate;
// }
//
// public String getAuditEventType() {
// return auditEventType;
// }
//
// public void setAuditEventType(String auditEventType) {
// this.auditEventType = auditEventType;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public void setData(Map<String, String> data) {
// this.data = data;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/repository/PersistenceAuditEventRepository.java
// public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, String> {
//
// List<PersistentAuditEvent> findByPrincipal(String principal);
//
// List<PersistentAuditEvent> findByPrincipalAndAuditEventDateGreaterThan(String principal, LocalDateTime after);
//
// @Query("select p from PersistentAuditEvent p where p.auditEventDate >= ?1 and p.auditEventDate <= ?2")
// List<PersistentAuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate);
// }
| import org.lightadmin.jhipster.config.audit.AuditEventConverter;
import org.lightadmin.jhipster.domain.PersistentAuditEvent;
import org.lightadmin.jhipster.repository.PersistenceAuditEventRepository;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List; | package org.lightadmin.jhipster.service;
/**
* Service for managing audit events.
* <p/>
* <p>
* This is the default implementation to support SpringBoot Actuator AuditEventRepository
* </p>
*/
@Service
@Transactional
public class AuditEventService {
@Inject
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Inject | // Path: src/main/java/org/lightadmin/jhipster/config/audit/AuditEventConverter.java
// @Configuration
// public class AuditEventConverter {
//
// /**
// * Convert a list of PersistentAuditEvent to a list of AuditEvent
// * @param persistentAuditEvents the list to convert
// * @return the converted list.
// */
// public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
// if (persistentAuditEvents == null) {
// return Collections.emptyList();
// }
//
// List<AuditEvent> auditEvents = new ArrayList<>();
//
// for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
// AuditEvent auditEvent = new AuditEvent(persistentAuditEvent.getAuditEventDate().toDate(), persistentAuditEvent.getPrincipal(),
// persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
// auditEvents.add(auditEvent);
// }
//
// return auditEvents;
// }
//
// /**
// * Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
// *
// * @param data the data to convert
// * @return a map of String, Object
// */
// public Map<String, Object> convertDataToObjects(Map<String, String> data) {
// Map<String, Object> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// results.put(key, data.get(key));
// }
// }
//
// return results;
// }
//
// /**
// * Internal conversion. This method will allow to save additionnals data.
// * By default, it will save the object as string
// *
// * @param data the data to convert
// * @return a map of String, String
// */
// public Map<String, String> convertDataToStrings(Map<String, Object> data) {
// Map<String, String> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// Object object = data.get(key);
//
// // Extract the data that will be saved.
// if (object instanceof WebAuthenticationDetails) {
// WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) object;
// results.put("remoteAddress", authenticationDetails.getRemoteAddress());
// results.put("sessionId", authenticationDetails.getSessionId());
// } else {
// results.put(key, object.toString());
// }
// }
// }
//
// return results;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/domain/PersistentAuditEvent.java
// @Entity
// @Table(name = "T_PERSISTENT_AUDIT_EVENT")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
// public class PersistentAuditEvent {
//
// @Id
// @GeneratedValue(strategy = GenerationType.TABLE)
// @Column(name = "event_id")
// private Long id;
//
// @NotNull
// private String principal;
//
// @Column(name = "event_date")
// @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
// private LocalDateTime auditEventDate;
//
// @Column(name = "event_type")
// private String auditEventType;
//
// @ElementCollection
// @MapKeyColumn(name="name")
// @Column(name="value")
// @CollectionTable(name="T_PERSISTENT_AUDIT_EVENT_DATA", joinColumns=@JoinColumn(name="event_id"))
// private Map<String, String> data = new HashMap<>();
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getPrincipal() {
// return principal;
// }
//
// public void setPrincipal(String principal) {
// this.principal = principal;
// }
//
// public LocalDateTime getAuditEventDate() {
// return auditEventDate;
// }
//
// public void setAuditEventDate(LocalDateTime auditEventDate) {
// this.auditEventDate = auditEventDate;
// }
//
// public String getAuditEventType() {
// return auditEventType;
// }
//
// public void setAuditEventType(String auditEventType) {
// this.auditEventType = auditEventType;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public void setData(Map<String, String> data) {
// this.data = data;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/repository/PersistenceAuditEventRepository.java
// public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, String> {
//
// List<PersistentAuditEvent> findByPrincipal(String principal);
//
// List<PersistentAuditEvent> findByPrincipalAndAuditEventDateGreaterThan(String principal, LocalDateTime after);
//
// @Query("select p from PersistentAuditEvent p where p.auditEventDate >= ?1 and p.auditEventDate <= ?2")
// List<PersistentAuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate);
// }
// Path: src/main/java/org/lightadmin/jhipster/service/AuditEventService.java
import org.lightadmin.jhipster.config.audit.AuditEventConverter;
import org.lightadmin.jhipster.domain.PersistentAuditEvent;
import org.lightadmin.jhipster.repository.PersistenceAuditEventRepository;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List;
package org.lightadmin.jhipster.service;
/**
* Service for managing audit events.
* <p/>
* <p>
* This is the default implementation to support SpringBoot Actuator AuditEventRepository
* </p>
*/
@Service
@Transactional
public class AuditEventService {
@Inject
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Inject | private AuditEventConverter auditEventConverter; |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/service/AuditEventService.java | // Path: src/main/java/org/lightadmin/jhipster/config/audit/AuditEventConverter.java
// @Configuration
// public class AuditEventConverter {
//
// /**
// * Convert a list of PersistentAuditEvent to a list of AuditEvent
// * @param persistentAuditEvents the list to convert
// * @return the converted list.
// */
// public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
// if (persistentAuditEvents == null) {
// return Collections.emptyList();
// }
//
// List<AuditEvent> auditEvents = new ArrayList<>();
//
// for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
// AuditEvent auditEvent = new AuditEvent(persistentAuditEvent.getAuditEventDate().toDate(), persistentAuditEvent.getPrincipal(),
// persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
// auditEvents.add(auditEvent);
// }
//
// return auditEvents;
// }
//
// /**
// * Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
// *
// * @param data the data to convert
// * @return a map of String, Object
// */
// public Map<String, Object> convertDataToObjects(Map<String, String> data) {
// Map<String, Object> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// results.put(key, data.get(key));
// }
// }
//
// return results;
// }
//
// /**
// * Internal conversion. This method will allow to save additionnals data.
// * By default, it will save the object as string
// *
// * @param data the data to convert
// * @return a map of String, String
// */
// public Map<String, String> convertDataToStrings(Map<String, Object> data) {
// Map<String, String> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// Object object = data.get(key);
//
// // Extract the data that will be saved.
// if (object instanceof WebAuthenticationDetails) {
// WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) object;
// results.put("remoteAddress", authenticationDetails.getRemoteAddress());
// results.put("sessionId", authenticationDetails.getSessionId());
// } else {
// results.put(key, object.toString());
// }
// }
// }
//
// return results;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/domain/PersistentAuditEvent.java
// @Entity
// @Table(name = "T_PERSISTENT_AUDIT_EVENT")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
// public class PersistentAuditEvent {
//
// @Id
// @GeneratedValue(strategy = GenerationType.TABLE)
// @Column(name = "event_id")
// private Long id;
//
// @NotNull
// private String principal;
//
// @Column(name = "event_date")
// @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
// private LocalDateTime auditEventDate;
//
// @Column(name = "event_type")
// private String auditEventType;
//
// @ElementCollection
// @MapKeyColumn(name="name")
// @Column(name="value")
// @CollectionTable(name="T_PERSISTENT_AUDIT_EVENT_DATA", joinColumns=@JoinColumn(name="event_id"))
// private Map<String, String> data = new HashMap<>();
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getPrincipal() {
// return principal;
// }
//
// public void setPrincipal(String principal) {
// this.principal = principal;
// }
//
// public LocalDateTime getAuditEventDate() {
// return auditEventDate;
// }
//
// public void setAuditEventDate(LocalDateTime auditEventDate) {
// this.auditEventDate = auditEventDate;
// }
//
// public String getAuditEventType() {
// return auditEventType;
// }
//
// public void setAuditEventType(String auditEventType) {
// this.auditEventType = auditEventType;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public void setData(Map<String, String> data) {
// this.data = data;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/repository/PersistenceAuditEventRepository.java
// public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, String> {
//
// List<PersistentAuditEvent> findByPrincipal(String principal);
//
// List<PersistentAuditEvent> findByPrincipalAndAuditEventDateGreaterThan(String principal, LocalDateTime after);
//
// @Query("select p from PersistentAuditEvent p where p.auditEventDate >= ?1 and p.auditEventDate <= ?2")
// List<PersistentAuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate);
// }
| import org.lightadmin.jhipster.config.audit.AuditEventConverter;
import org.lightadmin.jhipster.domain.PersistentAuditEvent;
import org.lightadmin.jhipster.repository.PersistenceAuditEventRepository;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List; | package org.lightadmin.jhipster.service;
/**
* Service for managing audit events.
* <p/>
* <p>
* This is the default implementation to support SpringBoot Actuator AuditEventRepository
* </p>
*/
@Service
@Transactional
public class AuditEventService {
@Inject
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Inject
private AuditEventConverter auditEventConverter;
public List<AuditEvent> findAll() {
return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
}
public List<AuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate) { | // Path: src/main/java/org/lightadmin/jhipster/config/audit/AuditEventConverter.java
// @Configuration
// public class AuditEventConverter {
//
// /**
// * Convert a list of PersistentAuditEvent to a list of AuditEvent
// * @param persistentAuditEvents the list to convert
// * @return the converted list.
// */
// public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
// if (persistentAuditEvents == null) {
// return Collections.emptyList();
// }
//
// List<AuditEvent> auditEvents = new ArrayList<>();
//
// for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
// AuditEvent auditEvent = new AuditEvent(persistentAuditEvent.getAuditEventDate().toDate(), persistentAuditEvent.getPrincipal(),
// persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
// auditEvents.add(auditEvent);
// }
//
// return auditEvents;
// }
//
// /**
// * Internal conversion. This is needed to support the current SpringBoot actuator AuditEventRepository interface
// *
// * @param data the data to convert
// * @return a map of String, Object
// */
// public Map<String, Object> convertDataToObjects(Map<String, String> data) {
// Map<String, Object> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// results.put(key, data.get(key));
// }
// }
//
// return results;
// }
//
// /**
// * Internal conversion. This method will allow to save additionnals data.
// * By default, it will save the object as string
// *
// * @param data the data to convert
// * @return a map of String, String
// */
// public Map<String, String> convertDataToStrings(Map<String, Object> data) {
// Map<String, String> results = new HashMap<>();
//
// if (data != null) {
// for (String key : data.keySet()) {
// Object object = data.get(key);
//
// // Extract the data that will be saved.
// if (object instanceof WebAuthenticationDetails) {
// WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) object;
// results.put("remoteAddress", authenticationDetails.getRemoteAddress());
// results.put("sessionId", authenticationDetails.getSessionId());
// } else {
// results.put(key, object.toString());
// }
// }
// }
//
// return results;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/domain/PersistentAuditEvent.java
// @Entity
// @Table(name = "T_PERSISTENT_AUDIT_EVENT")
// @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
// public class PersistentAuditEvent {
//
// @Id
// @GeneratedValue(strategy = GenerationType.TABLE)
// @Column(name = "event_id")
// private Long id;
//
// @NotNull
// private String principal;
//
// @Column(name = "event_date")
// @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
// private LocalDateTime auditEventDate;
//
// @Column(name = "event_type")
// private String auditEventType;
//
// @ElementCollection
// @MapKeyColumn(name="name")
// @Column(name="value")
// @CollectionTable(name="T_PERSISTENT_AUDIT_EVENT_DATA", joinColumns=@JoinColumn(name="event_id"))
// private Map<String, String> data = new HashMap<>();
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getPrincipal() {
// return principal;
// }
//
// public void setPrincipal(String principal) {
// this.principal = principal;
// }
//
// public LocalDateTime getAuditEventDate() {
// return auditEventDate;
// }
//
// public void setAuditEventDate(LocalDateTime auditEventDate) {
// this.auditEventDate = auditEventDate;
// }
//
// public String getAuditEventType() {
// return auditEventType;
// }
//
// public void setAuditEventType(String auditEventType) {
// this.auditEventType = auditEventType;
// }
//
// public Map<String, String> getData() {
// return data;
// }
//
// public void setData(Map<String, String> data) {
// this.data = data;
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/repository/PersistenceAuditEventRepository.java
// public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, String> {
//
// List<PersistentAuditEvent> findByPrincipal(String principal);
//
// List<PersistentAuditEvent> findByPrincipalAndAuditEventDateGreaterThan(String principal, LocalDateTime after);
//
// @Query("select p from PersistentAuditEvent p where p.auditEventDate >= ?1 and p.auditEventDate <= ?2")
// List<PersistentAuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate);
// }
// Path: src/main/java/org/lightadmin/jhipster/service/AuditEventService.java
import org.lightadmin.jhipster.config.audit.AuditEventConverter;
import org.lightadmin.jhipster.domain.PersistentAuditEvent;
import org.lightadmin.jhipster.repository.PersistenceAuditEventRepository;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List;
package org.lightadmin.jhipster.service;
/**
* Service for managing audit events.
* <p/>
* <p>
* This is the default implementation to support SpringBoot Actuator AuditEventRepository
* </p>
*/
@Service
@Transactional
public class AuditEventService {
@Inject
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Inject
private AuditEventConverter auditEventConverter;
public List<AuditEvent> findAll() {
return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
}
public List<AuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate) { | final List<PersistentAuditEvent> persistentAuditEvents = |
la-team/lightadmin-jhipster | src/test/java/org/lightadmin/jhipster/web/rest/UserResourceTest.java | // Path: src/main/java/org/lightadmin/jhipster/Application.java
// @ComponentScan
// @EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})
// public class Application {
//
// private final Logger log = LoggerFactory.getLogger(Application.class);
//
// @Inject
// private Environment env;
//
// /**
// * Initializes lightadmin-jhipster.
// * <p/>
// * Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile
// * <p/>
// */
// @PostConstruct
// public void initApplication() throws IOException {
// if (env.getActiveProfiles().length == 0) {
// log.warn("No Spring profile configured, running with default configuration");
// } else {
// log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
// }
// }
//
// /**
// * Main method, used to run the application.
// *
// * To run the application with hot reload enabled, add the following arguments to your JVM:
// * "-javaagent:spring_loaded/springloaded-jhipster.jar -noverify -Dspringloaded=plugins=io.github.jhipster.loaded.instrument.JHipsterLoadtimeInstrumentationPlugin"
// */
// public static void main(String[] args) {
// SpringApplication app = new SpringApplication(Application.class);
// app.setShowBanner(false);
//
// SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
//
// // Check if the selected profile has been set as argument.
// // if not the development profile will be added
// addDefaultProfile(app, source);
//
// app.run(args);
// }
//
// /**
// * Set a default profile if it has not been set
// */
// private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
// if (!source.containsProperty("spring.profiles.active")) {
// app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
// }
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/repository/UserRepository.java
// public interface UserRepository extends JpaRepository<User, String> {
//
// @Query("select u from User u where u.activationKey = ?1")
// User getUserByActivationKey(String activationKey);
//
// @Query("select u from User u where u.activated = false and u.createdDate > ?1")
// List<User> findNotActivatedUsersByCreationDateBefore(DateTime dateTime);
//
// }
| import org.lightadmin.jhipster.Application;
import org.lightadmin.jhipster.repository.UserRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import javax.inject.Inject;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; | package org.lightadmin.jhipster.web.rest;
/**
* Test class for the UserResource REST controller.
*
* @see UserResource
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@DirtiesContext(classMode= DirtiesContext.ClassMode.AFTER_CLASS)
@ActiveProfiles("dev")
public class UserResourceTest {
@Inject | // Path: src/main/java/org/lightadmin/jhipster/Application.java
// @ComponentScan
// @EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})
// public class Application {
//
// private final Logger log = LoggerFactory.getLogger(Application.class);
//
// @Inject
// private Environment env;
//
// /**
// * Initializes lightadmin-jhipster.
// * <p/>
// * Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile
// * <p/>
// */
// @PostConstruct
// public void initApplication() throws IOException {
// if (env.getActiveProfiles().length == 0) {
// log.warn("No Spring profile configured, running with default configuration");
// } else {
// log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
// }
// }
//
// /**
// * Main method, used to run the application.
// *
// * To run the application with hot reload enabled, add the following arguments to your JVM:
// * "-javaagent:spring_loaded/springloaded-jhipster.jar -noverify -Dspringloaded=plugins=io.github.jhipster.loaded.instrument.JHipsterLoadtimeInstrumentationPlugin"
// */
// public static void main(String[] args) {
// SpringApplication app = new SpringApplication(Application.class);
// app.setShowBanner(false);
//
// SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
//
// // Check if the selected profile has been set as argument.
// // if not the development profile will be added
// addDefaultProfile(app, source);
//
// app.run(args);
// }
//
// /**
// * Set a default profile if it has not been set
// */
// private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
// if (!source.containsProperty("spring.profiles.active")) {
// app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
// }
// }
// }
//
// Path: src/main/java/org/lightadmin/jhipster/repository/UserRepository.java
// public interface UserRepository extends JpaRepository<User, String> {
//
// @Query("select u from User u where u.activationKey = ?1")
// User getUserByActivationKey(String activationKey);
//
// @Query("select u from User u where u.activated = false and u.createdDate > ?1")
// List<User> findNotActivatedUsersByCreationDateBefore(DateTime dateTime);
//
// }
// Path: src/test/java/org/lightadmin/jhipster/web/rest/UserResourceTest.java
import org.lightadmin.jhipster.Application;
import org.lightadmin.jhipster.repository.UserRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import javax.inject.Inject;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
package org.lightadmin.jhipster.web.rest;
/**
* Test class for the UserResource REST controller.
*
* @see UserResource
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@DirtiesContext(classMode= DirtiesContext.ClassMode.AFTER_CLASS)
@ActiveProfiles("dev")
public class UserResourceTest {
@Inject | private UserRepository userRepository; |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/config/LocaleConfiguration.java | // Path: src/main/java/org/lightadmin/jhipster/config/locale/AngularCookieLocaleResolver.java
// public class AngularCookieLocaleResolver extends CookieLocaleResolver {
//
// @Override
// public Locale resolveLocale(HttpServletRequest request) {
// parseLocaleCookieIfNecessary(request);
// return (Locale) request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME);
// }
//
// @Override
// public LocaleContext resolveLocaleContext(final HttpServletRequest request) {
// parseLocaleCookieIfNecessary(request);
// return new TimeZoneAwareLocaleContext() {
// @Override
// public Locale getLocale() {
// return (Locale) request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME);
// }
// @Override
// public TimeZone getTimeZone() {
// return (TimeZone) request.getAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME);
// }
// };
// }
//
// @Override
// public void addCookie(HttpServletResponse response, String cookieValue) {
// // Mandatory cookie modification for angular to support the locale switching on the server side.
// cookieValue = "%22" + cookieValue + "%22";
// super.addCookie(response, cookieValue);
// }
//
// private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
// if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
// // Retrieve and parse cookie value.
// Cookie cookie = WebUtils.getCookie(request, getCookieName());
// Locale locale = null;
// TimeZone timeZone = null;
// if (cookie != null) {
// String value = cookie.getValue();
//
// // Remove the double quote
// value = StringUtils.replace(value, "%22", "");
//
// String localePart = value;
// String timeZonePart = null;
// int spaceIndex = localePart.indexOf(' ');
// if (spaceIndex != -1) {
// localePart = value.substring(0, spaceIndex);
// timeZonePart = value.substring(spaceIndex + 1);
// }
// locale = (!"-".equals(localePart) ? StringUtils.parseLocaleString(localePart) : null);
// if (timeZonePart != null) {
// timeZone = StringUtils.parseTimeZoneString(timeZonePart);
// }
// if (logger.isTraceEnabled()) {
// logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
// "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
// }
// }
// request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
// (locale != null ? locale: determineDefaultLocale(request)));
//
// request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
// (timeZone != null ? timeZone : determineDefaultTimeZone(request)));
// }
// }
// }
| import org.lightadmin.jhipster.config.locale.AngularCookieLocaleResolver;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; | package org.lightadmin.jhipster.config;
@Configuration
public class LocaleConfiguration extends WebMvcConfigurerAdapter implements EnvironmentAware {
private RelaxedPropertyResolver propertyResolver;
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.messageSource.");
}
@Bean(name = "localeResolver")
public LocaleResolver localeResolver() { | // Path: src/main/java/org/lightadmin/jhipster/config/locale/AngularCookieLocaleResolver.java
// public class AngularCookieLocaleResolver extends CookieLocaleResolver {
//
// @Override
// public Locale resolveLocale(HttpServletRequest request) {
// parseLocaleCookieIfNecessary(request);
// return (Locale) request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME);
// }
//
// @Override
// public LocaleContext resolveLocaleContext(final HttpServletRequest request) {
// parseLocaleCookieIfNecessary(request);
// return new TimeZoneAwareLocaleContext() {
// @Override
// public Locale getLocale() {
// return (Locale) request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME);
// }
// @Override
// public TimeZone getTimeZone() {
// return (TimeZone) request.getAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME);
// }
// };
// }
//
// @Override
// public void addCookie(HttpServletResponse response, String cookieValue) {
// // Mandatory cookie modification for angular to support the locale switching on the server side.
// cookieValue = "%22" + cookieValue + "%22";
// super.addCookie(response, cookieValue);
// }
//
// private void parseLocaleCookieIfNecessary(HttpServletRequest request) {
// if (request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME) == null) {
// // Retrieve and parse cookie value.
// Cookie cookie = WebUtils.getCookie(request, getCookieName());
// Locale locale = null;
// TimeZone timeZone = null;
// if (cookie != null) {
// String value = cookie.getValue();
//
// // Remove the double quote
// value = StringUtils.replace(value, "%22", "");
//
// String localePart = value;
// String timeZonePart = null;
// int spaceIndex = localePart.indexOf(' ');
// if (spaceIndex != -1) {
// localePart = value.substring(0, spaceIndex);
// timeZonePart = value.substring(spaceIndex + 1);
// }
// locale = (!"-".equals(localePart) ? StringUtils.parseLocaleString(localePart) : null);
// if (timeZonePart != null) {
// timeZone = StringUtils.parseTimeZoneString(timeZonePart);
// }
// if (logger.isTraceEnabled()) {
// logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale +
// "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : ""));
// }
// }
// request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME,
// (locale != null ? locale: determineDefaultLocale(request)));
//
// request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME,
// (timeZone != null ? timeZone : determineDefaultTimeZone(request)));
// }
// }
// }
// Path: src/main/java/org/lightadmin/jhipster/config/LocaleConfiguration.java
import org.lightadmin.jhipster.config.locale.AngularCookieLocaleResolver;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
package org.lightadmin.jhipster.config;
@Configuration
public class LocaleConfiguration extends WebMvcConfigurerAdapter implements EnvironmentAware {
private RelaxedPropertyResolver propertyResolver;
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.messageSource.");
}
@Bean(name = "localeResolver")
public LocaleResolver localeResolver() { | final AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver(); |
la-team/lightadmin-jhipster | src/main/java/org/lightadmin/jhipster/security/SpringSecurityAuditorAware.java | // Path: src/main/java/org/lightadmin/jhipster/config/Constants.java
// public interface Constants {
//
// public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
// public static final String SPRING_PROFILE_PRODUCTION = "prod";
// public static final String SYSTEM_ACCOUNT = "system";
//
// }
| import org.lightadmin.jhipster.config.Constants;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component; | package org.lightadmin.jhipster.security;
/**
* Implementation of AuditorAware based on Spring Security.
*/
@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {
public String getCurrentAuditor() {
String userName = SecurityUtils.getCurrentLogin(); | // Path: src/main/java/org/lightadmin/jhipster/config/Constants.java
// public interface Constants {
//
// public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
// public static final String SPRING_PROFILE_PRODUCTION = "prod";
// public static final String SYSTEM_ACCOUNT = "system";
//
// }
// Path: src/main/java/org/lightadmin/jhipster/security/SpringSecurityAuditorAware.java
import org.lightadmin.jhipster.config.Constants;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
package org.lightadmin.jhipster.security;
/**
* Implementation of AuditorAware based on Spring Security.
*/
@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {
public String getCurrentAuditor() {
String userName = SecurityUtils.getCurrentLogin(); | return (userName != null ? userName : Constants.SYSTEM_ACCOUNT); |
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/util/RequestExecutor.java | // Path: src/main/java/com/googlecode/batchfb/util/RequestBuilder.java
// public static interface HttpResponse {
// /** The http response code */
// int getResponseCode() throws IOException;
// /** The body content of the response */
// InputStream getContentStream() throws IOException;
// }
| import java.io.IOException;
import com.googlecode.batchfb.util.RequestBuilder.HttpResponse;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.util;
/**
* <p>Allows requests to be executed given the character of a particular platform or http library.</p>
*
* @author Jeff Schnitzer
*/
abstract public class RequestExecutor {
/** */
private static RequestExecutor current;
/** Gets the current factory */
public static RequestExecutor instance() { return current; }
/**
* Sets the current factory used, overriding the default discovery process.
*/
public static void setInstance(RequestExecutor value) { current = value; }
/**
* The discovery process
*/
static {
if (System.getProperty("com.google.appengine.runtime.environment") != null)
current = new AppengineRequestExecutor();
else
current = new DefaultRequestExecutor();
}
/**
* Executes the specified request, up to the number of retries allowed.
*/
| // Path: src/main/java/com/googlecode/batchfb/util/RequestBuilder.java
// public static interface HttpResponse {
// /** The http response code */
// int getResponseCode() throws IOException;
// /** The body content of the response */
// InputStream getContentStream() throws IOException;
// }
// Path: src/main/java/com/googlecode/batchfb/util/RequestExecutor.java
import java.io.IOException;
import com.googlecode.batchfb.util.RequestBuilder.HttpResponse;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.util;
/**
* <p>Allows requests to be executed given the character of a particular platform or http library.</p>
*
* @author Jeff Schnitzer
*/
abstract public class RequestExecutor {
/** */
private static RequestExecutor current;
/** Gets the current factory */
public static RequestExecutor instance() { return current; }
/**
* Sets the current factory used, overriding the default discovery process.
*/
public static void setInstance(RequestExecutor value) { current = value; }
/**
* The discovery process
*/
static {
if (System.getProperty("com.google.appengine.runtime.environment") != null)
current = new AppengineRequestExecutor();
else
current = new DefaultRequestExecutor();
}
/**
* Executes the specified request, up to the number of retries allowed.
*/
| abstract public HttpResponse execute(int retries, RequestSetup setup) throws IOException;
|
stickfigure/batchfb | src/test/java/com/googlecode/batchfb/test/QueryResultSizeTest.java | // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
| import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.Later;
import java.net.URL;
import java.net.URLEncoder;
import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Testing a report that sometimes query results return the wrong size.
*
* @author Jeff Schnitzer
*/
public class QueryResultSizeTest extends TestBase {
/**
*/
@Test
public void basicQuery() throws Exception {
this.ensureQueryIsCorrectSize("SELECT aid FROM album WHERE owner = me()");
}
/**
* This query takes a while to run
*/
@Test
public void biggerQuery() throws Exception {
this.ensureQueryIsCorrectSize("SELECT aid, owner, cover_pid, created, name, description, size, type FROM album WHERE owner IN (SELECT uid2 FROM friend WHERE uid1 = me()) OR owner = me()");
}
/**
* Run the query through BatchFB and by hand and ensure the result set is same size.
*/
private void ensureQueryIsCorrectSize(String query) throws Exception {
String url = "https://api.facebook.com/method/fql.query?format=json&query=" + URLEncoder.encode(query, "utf-8")
+ "&access_token=" + ACCESS_TOKEN;
URL manual = new URL(url);
System.out.println("Manual URL is: " + url);
JsonNode manualNodes = new ObjectMapper().readTree(manual.openStream());
assert manualNodes instanceof ArrayNode;
| // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
// Path: src/test/java/com/googlecode/batchfb/test/QueryResultSizeTest.java
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.Later;
import java.net.URL;
import java.net.URLEncoder;
import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Testing a report that sometimes query results return the wrong size.
*
* @author Jeff Schnitzer
*/
public class QueryResultSizeTest extends TestBase {
/**
*/
@Test
public void basicQuery() throws Exception {
this.ensureQueryIsCorrectSize("SELECT aid FROM album WHERE owner = me()");
}
/**
* This query takes a while to run
*/
@Test
public void biggerQuery() throws Exception {
this.ensureQueryIsCorrectSize("SELECT aid, owner, cover_pid, created, name, description, size, type FROM album WHERE owner IN (SELECT uid2 FROM friend WHERE uid1 = me()) OR owner = me()");
}
/**
* Run the query through BatchFB and by hand and ensure the result set is same size.
*/
private void ensureQueryIsCorrectSize(String query) throws Exception {
String url = "https://api.facebook.com/method/fql.query?format=json&query=" + URLEncoder.encode(query, "utf-8")
+ "&access_token=" + ACCESS_TOKEN;
URL manual = new URL(url);
System.out.println("Manual URL is: " + url);
JsonNode manualNodes = new ObjectMapper().readTree(manual.openStream());
assert manualNodes instanceof ArrayNode;
| Later<ArrayNode> nodes = this.authBatcher.query(query);
|
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/util/MultipartWriter.java | // Path: src/main/java/com/googlecode/batchfb/util/RequestBuilder.java
// public static class BinaryAttachment {
// InputStream data;
// String contentType;
// String filename;
//
// BinaryAttachment(InputStream data, String contentType, String filename) {
// this.data = data;
// this.contentType = contentType;
// this.filename = filename;
// }
// }
| import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import com.googlecode.batchfb.util.RequestBuilder.BinaryAttachment;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.util;
/**
* <p>Tool which writes multipart/form-data to a stream.</p>
*
* <p>See <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4">http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4</a>.</p>
*
* @author Jeff Schnitzer
*/
public class MultipartWriter {
/** */
private static final String MULTIPART_BOUNDARY = "**** an awful string which should never exist naturally ****" + Math.random();
private static final String MULTIPART_BOUNDARY_SEPARATOR = "--" + MULTIPART_BOUNDARY;
private static final String MULTIPART_BOUNDARY_END = MULTIPART_BOUNDARY_SEPARATOR + "--";
/** */
OutputStream out;
/** */
public MultipartWriter(RequestDefinition executor) throws IOException {
executor.setHeader("Content-Type", "multipart/form-data; boundary=" + MULTIPART_BOUNDARY);
this.out = executor.getContentOutputStream();
}
/**
* Write the params as multipart/form-data. Params can include BinaryAttachemnt objects.
*/
public void write(Map<String, Object> params) throws IOException {
LineWriter writer = new LineWriter(this.out);
try {
for (Map.Entry<String, Object> param: params.entrySet()) {
writer.println(MULTIPART_BOUNDARY_SEPARATOR);
| // Path: src/main/java/com/googlecode/batchfb/util/RequestBuilder.java
// public static class BinaryAttachment {
// InputStream data;
// String contentType;
// String filename;
//
// BinaryAttachment(InputStream data, String contentType, String filename) {
// this.data = data;
// this.contentType = contentType;
// this.filename = filename;
// }
// }
// Path: src/main/java/com/googlecode/batchfb/util/MultipartWriter.java
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import com.googlecode.batchfb.util.RequestBuilder.BinaryAttachment;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.util;
/**
* <p>Tool which writes multipart/form-data to a stream.</p>
*
* <p>See <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4">http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4</a>.</p>
*
* @author Jeff Schnitzer
*/
public class MultipartWriter {
/** */
private static final String MULTIPART_BOUNDARY = "**** an awful string which should never exist naturally ****" + Math.random();
private static final String MULTIPART_BOUNDARY_SEPARATOR = "--" + MULTIPART_BOUNDARY;
private static final String MULTIPART_BOUNDARY_END = MULTIPART_BOUNDARY_SEPARATOR + "--";
/** */
OutputStream out;
/** */
public MultipartWriter(RequestDefinition executor) throws IOException {
executor.setHeader("Content-Type", "multipart/form-data; boundary=" + MULTIPART_BOUNDARY);
this.out = executor.getContentOutputStream();
}
/**
* Write the params as multipart/form-data. Params can include BinaryAttachemnt objects.
*/
public void write(Map<String, Object> params) throws IOException {
LineWriter writer = new LineWriter(this.out);
try {
for (Map.Entry<String, Object> param: params.entrySet()) {
writer.println(MULTIPART_BOUNDARY_SEPARATOR);
| if (param.getValue() instanceof BinaryAttachment) {
|
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/impl/MapperWrapper.java | // Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/LaterWrapper.java
// public class LaterWrapper<K, V> implements Later<V>
// {
// private Later<K> orig;
// private V cached;
//
// public LaterWrapper(Later<K> orig)
// {
// this.orig = orig;
// }
//
// @Override
// public V get() throws FacebookException
// {
// if (this.cached == null)
// this.cached = this.convert(this.orig.get());
//
// return this.cached;
// }
//
// /** Override this; default is just to pass through which will be unsafe if types are incompatible */
// @SuppressWarnings("unchecked")
// protected V convert(K data)
// {
// return (V)data;
// }
// }
| import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.util.LaterWrapper; | /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.impl;
/**
* Wrapper that converts from a JsonNode to an actual Java object.
*/
public class MapperWrapper<T> extends LaterWrapper<JsonNode, T> {
JavaType resultType;
ObjectMapper mapper;
/**
* @param base is assumed to produce the real deal, not an error node
*/ | // Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/LaterWrapper.java
// public class LaterWrapper<K, V> implements Later<V>
// {
// private Later<K> orig;
// private V cached;
//
// public LaterWrapper(Later<K> orig)
// {
// this.orig = orig;
// }
//
// @Override
// public V get() throws FacebookException
// {
// if (this.cached == null)
// this.cached = this.convert(this.orig.get());
//
// return this.cached;
// }
//
// /** Override this; default is just to pass through which will be unsafe if types are incompatible */
// @SuppressWarnings("unchecked")
// protected V convert(K data)
// {
// return (V)data;
// }
// }
// Path: src/main/java/com/googlecode/batchfb/impl/MapperWrapper.java
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.util.LaterWrapper;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.impl;
/**
* Wrapper that converts from a JsonNode to an actual Java object.
*/
public class MapperWrapper<T> extends LaterWrapper<JsonNode, T> {
JavaType resultType;
ObjectMapper mapper;
/**
* @param base is assumed to produce the real deal, not an error node
*/ | public MapperWrapper(JavaType resultType, ObjectMapper mapper, Later<JsonNode> base) { |
stickfigure/batchfb | src/test/java/com/googlecode/batchfb/test/MultiqueryTest.java | // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/QueryRequest.java
// public class QueryRequest<T> extends Request<T> {
// String fql;
// public String getFQL() { return this.fql; }
//
// /** */
// public QueryRequest(String fql, String name, Later<T> source) {
// super(source);
//
// this.fql = fql;
// this.setName(name);
// }
// }
| import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.QueryRequest;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Testing out batching of multiqueries.
*
* @author Jeff Schnitzer
*/
public class MultiqueryTest extends TestBase {
/**
*/
@Test
public void basicMultiquery() throws Exception {
| // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/QueryRequest.java
// public class QueryRequest<T> extends Request<T> {
// String fql;
// public String getFQL() { return this.fql; }
//
// /** */
// public QueryRequest(String fql, String name, Later<T> source) {
// super(source);
//
// this.fql = fql;
// this.setName(name);
// }
// }
// Path: src/test/java/com/googlecode/batchfb/test/MultiqueryTest.java
import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.QueryRequest;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Testing out batching of multiqueries.
*
* @author Jeff Schnitzer
*/
public class MultiqueryTest extends TestBase {
/**
*/
@Test
public void basicMultiquery() throws Exception {
| Later<ArrayNode> firstNameArray = this.authBatcher.query("SELECT first_name FROM user WHERE uid = 1047296661");
|
stickfigure/batchfb | src/test/java/com/googlecode/batchfb/test/MultiqueryTest.java | // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/QueryRequest.java
// public class QueryRequest<T> extends Request<T> {
// String fql;
// public String getFQL() { return this.fql; }
//
// /** */
// public QueryRequest(String fql, String name, Later<T> source) {
// super(source);
//
// this.fql = fql;
// this.setName(name);
// }
// }
| import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.QueryRequest;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Testing out batching of multiqueries.
*
* @author Jeff Schnitzer
*/
public class MultiqueryTest extends TestBase {
/**
*/
@Test
public void basicMultiquery() throws Exception {
Later<ArrayNode> firstNameArray = this.authBatcher.query("SELECT first_name FROM user WHERE uid = 1047296661");
Later<ArrayNode> lastNameArray = this.authBatcher.query("SELECT last_name FROM user WHERE uid = 1047296661");
assert 1 == firstNameArray.get().size();
assert 1 == lastNameArray.get().size();
assert "Robert".equals(firstNameArray.get().get(0).get("first_name").textValue());
assert "Dobbs".equals(lastNameArray.get().get(0).get("last_name").textValue());
}
/**
* What happened was the order went q1, q10, q11, q2, q3 and thus fucked it up. This should
* now work based on proper query name lookup.
*/
@Test
public void moreThanTenQueries() throws Exception {
Later<JsonNode> firstName = this.authBatcher.queryFirst("SELECT first_name FROM user WHERE uid = 1047296661");
Later<JsonNode> lastName = this.authBatcher.queryFirst("SELECT last_name FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
assert "Robert".equals(firstName.get().get("first_name").textValue());
assert "Dobbs".equals(lastName.get().get("last_name").textValue());
}
/**
* Make sure we can explicitly name queries
*/
@Test
public void namedQueries() throws Exception {
| // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/QueryRequest.java
// public class QueryRequest<T> extends Request<T> {
// String fql;
// public String getFQL() { return this.fql; }
//
// /** */
// public QueryRequest(String fql, String name, Later<T> source) {
// super(source);
//
// this.fql = fql;
// this.setName(name);
// }
// }
// Path: src/test/java/com/googlecode/batchfb/test/MultiqueryTest.java
import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.QueryRequest;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Testing out batching of multiqueries.
*
* @author Jeff Schnitzer
*/
public class MultiqueryTest extends TestBase {
/**
*/
@Test
public void basicMultiquery() throws Exception {
Later<ArrayNode> firstNameArray = this.authBatcher.query("SELECT first_name FROM user WHERE uid = 1047296661");
Later<ArrayNode> lastNameArray = this.authBatcher.query("SELECT last_name FROM user WHERE uid = 1047296661");
assert 1 == firstNameArray.get().size();
assert 1 == lastNameArray.get().size();
assert "Robert".equals(firstNameArray.get().get(0).get("first_name").textValue());
assert "Dobbs".equals(lastNameArray.get().get(0).get("last_name").textValue());
}
/**
* What happened was the order went q1, q10, q11, q2, q3 and thus fucked it up. This should
* now work based on proper query name lookup.
*/
@Test
public void moreThanTenQueries() throws Exception {
Later<JsonNode> firstName = this.authBatcher.queryFirst("SELECT first_name FROM user WHERE uid = 1047296661");
Later<JsonNode> lastName = this.authBatcher.queryFirst("SELECT last_name FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
this.authBatcher.queryFirst("SELECT pic_square FROM user WHERE uid = 1047296661");
assert "Robert".equals(firstName.get().get("first_name").textValue());
assert "Dobbs".equals(lastName.get().get("last_name").textValue());
}
/**
* Make sure we can explicitly name queries
*/
@Test
public void namedQueries() throws Exception {
| QueryRequest<ArrayNode> firstNameArray = this.authBatcher.query("SELECT first_name FROM user WHERE uid = 1047296661");
|
stickfigure/batchfb | src/test/java/com/googlecode/batchfb/test/BasicBatchTest.java | // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
| import java.util.List;
import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.Later;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Basic unit tests for the batching features
*
* @author Jeff Schnitzer
*/
public class BasicBatchTest extends TestBase {
/** */
static class User {
public String name;
}
/**
*/
@Test
public void singleGraphRequestAsNode() throws Exception {
| // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
// Path: src/test/java/com/googlecode/batchfb/test/BasicBatchTest.java
import java.util.List;
import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.Later;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Basic unit tests for the batching features
*
* @author Jeff Schnitzer
*/
public class BasicBatchTest extends TestBase {
/** */
static class User {
public String name;
}
/**
*/
@Test
public void singleGraphRequestAsNode() throws Exception {
| Later<JsonNode> node = this.authBatcher.graph("/1047296661");
|
stickfigure/batchfb | src/test/java/com/googlecode/batchfb/test/UtilsTest.java | // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/SplitterIterator.java
// public class SplitterIterator<T> implements Iterator<List<T>> {
//
// /** */
// int maxSize;
// Iterator<List<T>> original;
//
// /** These are only non-null if we are processing a too-big piece */
// List<T> whole;
// int offset;
// List<T> part;
//
// /** */
// public SplitterIterator(Collection<List<T>> coll, int maxSize) {
// this.maxSize = maxSize;
// this.original = coll.iterator();
// }
//
// @Override
// public boolean hasNext() {
// return this.original.hasNext() || this.whole != null;
// }
//
// @Override
// public List<T> next() {
// if (this.whole == null)
// this.whole = this.original.next();
//
// if (this.whole.size() - this.offset <= this.maxSize) {
// List<T> result = this.whole.subList(this.offset, this.whole.size());
// this.whole = null;
// this.part = null;
// this.offset = 0;
// return result;
// } else {
// this.part = this.whole.subList(this.offset, this.maxSize);
// this.offset += this.maxSize;
// return this.part;
// }
// }
//
// @Override
// public void remove() {
// if (this.part != null) {
// this.offset -= this.part.size();
// this.part.clear();
// } else {
// this.original.remove();
// }
// }
// }
| import com.googlecode.batchfb.util.SplitterIterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Tests of the utilities package
*
* @author Jeff Schnitzer
*/
public class UtilsTest extends TestBase {
/**
*/
@Test
public void splitterIteratorTest() throws Exception {
List<List<String>> master = new ArrayList<List<String>>();
LinkedList<String> w1 = new LinkedList<String>();
w1.add("a");
w1.add("b");
w1.add("c");
master.add(w1);
LinkedList<String> w2 = new LinkedList<String>();
w2.add("d");
w2.add("e");
w2.add("f");
master.add(w2);
| // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/SplitterIterator.java
// public class SplitterIterator<T> implements Iterator<List<T>> {
//
// /** */
// int maxSize;
// Iterator<List<T>> original;
//
// /** These are only non-null if we are processing a too-big piece */
// List<T> whole;
// int offset;
// List<T> part;
//
// /** */
// public SplitterIterator(Collection<List<T>> coll, int maxSize) {
// this.maxSize = maxSize;
// this.original = coll.iterator();
// }
//
// @Override
// public boolean hasNext() {
// return this.original.hasNext() || this.whole != null;
// }
//
// @Override
// public List<T> next() {
// if (this.whole == null)
// this.whole = this.original.next();
//
// if (this.whole.size() - this.offset <= this.maxSize) {
// List<T> result = this.whole.subList(this.offset, this.whole.size());
// this.whole = null;
// this.part = null;
// this.offset = 0;
// return result;
// } else {
// this.part = this.whole.subList(this.offset, this.maxSize);
// this.offset += this.maxSize;
// return this.part;
// }
// }
//
// @Override
// public void remove() {
// if (this.part != null) {
// this.offset -= this.part.size();
// this.part.clear();
// } else {
// this.original.remove();
// }
// }
// }
// Path: src/test/java/com/googlecode/batchfb/test/UtilsTest.java
import com.googlecode.batchfb.util.SplitterIterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Tests of the utilities package
*
* @author Jeff Schnitzer
*/
public class UtilsTest extends TestBase {
/**
*/
@Test
public void splitterIteratorTest() throws Exception {
List<List<String>> master = new ArrayList<List<String>>();
LinkedList<String> w1 = new LinkedList<String>();
w1.add("a");
w1.add("b");
w1.add("c");
master.add(w1);
LinkedList<String> w2 = new LinkedList<String>();
w2.add("d");
w2.add("e");
w2.add("f");
master.add(w2);
| Iterator<List<String>> splitter = new SplitterIterator<String>(master, 2);
|
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/util/URLParser.java | // Path: src/main/java/com/googlecode/batchfb/Param.java
// public class Param {
//
// /** */
// public final String name;
//
// /** Will be turned into a string (possibly json-mapped) later */
// public final Object value;
//
// /**
// * @param value must be something that can be converted to a String with toString().
// */
// public Param(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * @return a version useful for debugging.
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, value);
// }
// }
| import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
import com.googlecode.batchfb.Param;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.util;
/**
* <p>Parses a URL into its constituent parts, including the path and the parameters.
* This is really just a slightly smarter wrapper for java.net.URL. It assumes
* the URL is valid, which should be safe for Facebook's paging urls.</p>
*
* @author Jeff Schnitzer
*/
public class URLParser {
/**
* Breaks down a standard query string (ie "param1=foo¶m2=bar")
* @return an empty map if the query is empty or null
*/
public static Map<String, String> parseQuery(String query) {
Map<String, String> result = new LinkedHashMap<String, String>();
if (query != null) {
for (String keyValue: query.split("&")) {
String[] pair = keyValue.split("=");
result.put(StringUtils.urlDecode(pair[0]), StringUtils.urlDecode(pair[1]));
}
}
return result;
}
/** */
URL parsed;
Map<String, String> params;
/**
* @param url is assumed to be a valid url with properly encoded key=value pairs, nothing exotic
*/
public URLParser(String url) {
try {
this.parsed = new URL(url);
this.params = parseQuery(this.parsed.getQuery());
} catch (MalformedURLException e) { throw new RuntimeException(e); }
}
/**
* Get the params, or an empty map if there are none
*/
public Map<String, String> getParams() { return this.params; }
/**
* Gets the current state of the params as a Param[] array
*/
| // Path: src/main/java/com/googlecode/batchfb/Param.java
// public class Param {
//
// /** */
// public final String name;
//
// /** Will be turned into a string (possibly json-mapped) later */
// public final Object value;
//
// /**
// * @param value must be something that can be converted to a String with toString().
// */
// public Param(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * @return a version useful for debugging.
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, value);
// }
// }
// Path: src/main/java/com/googlecode/batchfb/util/URLParser.java
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
import com.googlecode.batchfb.Param;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.util;
/**
* <p>Parses a URL into its constituent parts, including the path and the parameters.
* This is really just a slightly smarter wrapper for java.net.URL. It assumes
* the URL is valid, which should be safe for Facebook's paging urls.</p>
*
* @author Jeff Schnitzer
*/
public class URLParser {
/**
* Breaks down a standard query string (ie "param1=foo¶m2=bar")
* @return an empty map if the query is empty or null
*/
public static Map<String, String> parseQuery(String query) {
Map<String, String> result = new LinkedHashMap<String, String>();
if (query != null) {
for (String keyValue: query.split("&")) {
String[] pair = keyValue.split("=");
result.put(StringUtils.urlDecode(pair[0]), StringUtils.urlDecode(pair[1]));
}
}
return result;
}
/** */
URL parsed;
Map<String, String> params;
/**
* @param url is assumed to be a valid url with properly encoded key=value pairs, nothing exotic
*/
public URLParser(String url) {
try {
this.parsed = new URL(url);
this.params = parseQuery(this.parsed.getQuery());
} catch (MalformedURLException e) { throw new RuntimeException(e); }
}
/**
* Get the params, or an empty map if there are none
*/
public Map<String, String> getParams() { return this.params; }
/**
* Gets the current state of the params as a Param[] array
*/
| public Param[] getParamsAsArray() {
|
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/GraphRequest.java | // Path: src/main/java/com/googlecode/batchfb/util/RequestBuilder.java
// public static enum HttpMethod {
// GET, POST, DELETE;
// }
| import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.batchfb.util.RequestBuilder.HttpMethod; | package com.googlecode.batchfb;
/**
* <p>Represents one graph request queued by the user.</p>
*/
public class GraphRequest<T> extends GraphRequestBase<T> {
@JsonIgnore
Param[] params;
/** Strips off any leading / from object */
public GraphRequest(String object, Param[] params, ObjectMapper mapper, Later<T> source) { | // Path: src/main/java/com/googlecode/batchfb/util/RequestBuilder.java
// public static enum HttpMethod {
// GET, POST, DELETE;
// }
// Path: src/main/java/com/googlecode/batchfb/GraphRequest.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.batchfb.util.RequestBuilder.HttpMethod;
package com.googlecode.batchfb;
/**
* <p>Represents one graph request queued by the user.</p>
*/
public class GraphRequest<T> extends GraphRequestBase<T> {
@JsonIgnore
Param[] params;
/** Strips off any leading / from object */
public GraphRequest(String object, Param[] params, ObjectMapper mapper, Later<T> source) { | this(object, HttpMethod.GET, params, mapper, source); |
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/impl/QueryNodeExtractor.java | // Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/Request.java
// public class Request<T> extends LaterWrapper<T, T> {
//
// private String name;
//
// public Request(Later<T> source) {
// super(source);
// }
//
// /**
// * A name that might be referenced later in other requests in the same batch.
// */
// public String getName() {
// return this.name;
// }
//
// /**
// * Set an explicit name that can be referenced later in other requests in the same batch.
// * This works within multiquery and within graph calls, but you can't use names across
// * the two types of batches.
// *
// * This method can be chained.
// */
// public Request<T> setName(String value) {
// this.name = value;
// return this;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/LaterWrapper.java
// public class LaterWrapper<K, V> implements Later<V>
// {
// private Later<K> orig;
// private V cached;
//
// public LaterWrapper(Later<K> orig)
// {
// this.orig = orig;
// }
//
// @Override
// public V get() throws FacebookException
// {
// if (this.cached == null)
// this.cached = this.convert(this.orig.get());
//
// return this.cached;
// }
//
// /** Override this; default is just to pass through which will be unsafe if types are incompatible */
// @SuppressWarnings("unchecked")
// protected V convert(K data)
// {
// return (V)data;
// }
// }
| import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.Request;
import com.googlecode.batchfb.util.LaterWrapper;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.impl;
/**
* <p>Knows how to get the JsonNode for a particular query request out of a multiquery.</p>
*
* <p>Sadly, this is what a multiquery result looks like:</p>
<pre>
[
{
"name": "query1",
"fql_result_set": [ { "uid": 503702723 } ]
},
{
"name": "query2",
"fql_result_set": [ { "uid": 503702723 } ]
}
]
</pre>
* <p>We'd like to use positional indexing but facebook reorders the results. So we basically need to
* scan through and look for our node. LAME.</p>
*
* <p>Because we need to know the name, the Request<?> (which holds the final name) must be set
* after this object is constructed but before it is executed. It can't be passed in on construction
* because the QueryNodeExtractor gets passed in (through a chain of wrappers) to the request.
*
* <p>More info available here:
* https://developers.facebook.com/docs/reference/rest/fql.multiquery/
* </p>
*/
public class QueryNodeExtractor extends LaterWrapper<JsonNode, JsonNode>
{
| // Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/Request.java
// public class Request<T> extends LaterWrapper<T, T> {
//
// private String name;
//
// public Request(Later<T> source) {
// super(source);
// }
//
// /**
// * A name that might be referenced later in other requests in the same batch.
// */
// public String getName() {
// return this.name;
// }
//
// /**
// * Set an explicit name that can be referenced later in other requests in the same batch.
// * This works within multiquery and within graph calls, but you can't use names across
// * the two types of batches.
// *
// * This method can be chained.
// */
// public Request<T> setName(String value) {
// this.name = value;
// return this;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/LaterWrapper.java
// public class LaterWrapper<K, V> implements Later<V>
// {
// private Later<K> orig;
// private V cached;
//
// public LaterWrapper(Later<K> orig)
// {
// this.orig = orig;
// }
//
// @Override
// public V get() throws FacebookException
// {
// if (this.cached == null)
// this.cached = this.convert(this.orig.get());
//
// return this.cached;
// }
//
// /** Override this; default is just to pass through which will be unsafe if types are incompatible */
// @SuppressWarnings("unchecked")
// protected V convert(K data)
// {
// return (V)data;
// }
// }
// Path: src/main/java/com/googlecode/batchfb/impl/QueryNodeExtractor.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.Request;
import com.googlecode.batchfb.util.LaterWrapper;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.impl;
/**
* <p>Knows how to get the JsonNode for a particular query request out of a multiquery.</p>
*
* <p>Sadly, this is what a multiquery result looks like:</p>
<pre>
[
{
"name": "query1",
"fql_result_set": [ { "uid": 503702723 } ]
},
{
"name": "query2",
"fql_result_set": [ { "uid": 503702723 } ]
}
]
</pre>
* <p>We'd like to use positional indexing but facebook reorders the results. So we basically need to
* scan through and look for our node. LAME.</p>
*
* <p>Because we need to know the name, the Request<?> (which holds the final name) must be set
* after this object is constructed but before it is executed. It can't be passed in on construction
* because the QueryNodeExtractor gets passed in (through a chain of wrappers) to the request.
*
* <p>More info available here:
* https://developers.facebook.com/docs/reference/rest/fql.multiquery/
* </p>
*/
public class QueryNodeExtractor extends LaterWrapper<JsonNode, JsonNode>
{
| Request<?> request;
|
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/impl/QueryNodeExtractor.java | // Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/Request.java
// public class Request<T> extends LaterWrapper<T, T> {
//
// private String name;
//
// public Request(Later<T> source) {
// super(source);
// }
//
// /**
// * A name that might be referenced later in other requests in the same batch.
// */
// public String getName() {
// return this.name;
// }
//
// /**
// * Set an explicit name that can be referenced later in other requests in the same batch.
// * This works within multiquery and within graph calls, but you can't use names across
// * the two types of batches.
// *
// * This method can be chained.
// */
// public Request<T> setName(String value) {
// this.name = value;
// return this;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/LaterWrapper.java
// public class LaterWrapper<K, V> implements Later<V>
// {
// private Later<K> orig;
// private V cached;
//
// public LaterWrapper(Later<K> orig)
// {
// this.orig = orig;
// }
//
// @Override
// public V get() throws FacebookException
// {
// if (this.cached == null)
// this.cached = this.convert(this.orig.get());
//
// return this.cached;
// }
//
// /** Override this; default is just to pass through which will be unsafe if types are incompatible */
// @SuppressWarnings("unchecked")
// protected V convert(K data)
// {
// return (V)data;
// }
// }
| import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.Request;
import com.googlecode.batchfb.util.LaterWrapper;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.impl;
/**
* <p>Knows how to get the JsonNode for a particular query request out of a multiquery.</p>
*
* <p>Sadly, this is what a multiquery result looks like:</p>
<pre>
[
{
"name": "query1",
"fql_result_set": [ { "uid": 503702723 } ]
},
{
"name": "query2",
"fql_result_set": [ { "uid": 503702723 } ]
}
]
</pre>
* <p>We'd like to use positional indexing but facebook reorders the results. So we basically need to
* scan through and look for our node. LAME.</p>
*
* <p>Because we need to know the name, the Request<?> (which holds the final name) must be set
* after this object is constructed but before it is executed. It can't be passed in on construction
* because the QueryNodeExtractor gets passed in (through a chain of wrappers) to the request.
*
* <p>More info available here:
* https://developers.facebook.com/docs/reference/rest/fql.multiquery/
* </p>
*/
public class QueryNodeExtractor extends LaterWrapper<JsonNode, JsonNode>
{
Request<?> request;
/**
* @param multiqueryResult should be the graph selection of a MultiqueryRequest
*/
| // Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/Request.java
// public class Request<T> extends LaterWrapper<T, T> {
//
// private String name;
//
// public Request(Later<T> source) {
// super(source);
// }
//
// /**
// * A name that might be referenced later in other requests in the same batch.
// */
// public String getName() {
// return this.name;
// }
//
// /**
// * Set an explicit name that can be referenced later in other requests in the same batch.
// * This works within multiquery and within graph calls, but you can't use names across
// * the two types of batches.
// *
// * This method can be chained.
// */
// public Request<T> setName(String value) {
// this.name = value;
// return this;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/LaterWrapper.java
// public class LaterWrapper<K, V> implements Later<V>
// {
// private Later<K> orig;
// private V cached;
//
// public LaterWrapper(Later<K> orig)
// {
// this.orig = orig;
// }
//
// @Override
// public V get() throws FacebookException
// {
// if (this.cached == null)
// this.cached = this.convert(this.orig.get());
//
// return this.cached;
// }
//
// /** Override this; default is just to pass through which will be unsafe if types are incompatible */
// @SuppressWarnings("unchecked")
// protected V convert(K data)
// {
// return (V)data;
// }
// }
// Path: src/main/java/com/googlecode/batchfb/impl/QueryNodeExtractor.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.Request;
import com.googlecode.batchfb.util.LaterWrapper;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.impl;
/**
* <p>Knows how to get the JsonNode for a particular query request out of a multiquery.</p>
*
* <p>Sadly, this is what a multiquery result looks like:</p>
<pre>
[
{
"name": "query1",
"fql_result_set": [ { "uid": 503702723 } ]
},
{
"name": "query2",
"fql_result_set": [ { "uid": 503702723 } ]
}
]
</pre>
* <p>We'd like to use positional indexing but facebook reorders the results. So we basically need to
* scan through and look for our node. LAME.</p>
*
* <p>Because we need to know the name, the Request<?> (which holds the final name) must be set
* after this object is constructed but before it is executed. It can't be passed in on construction
* because the QueryNodeExtractor gets passed in (through a chain of wrappers) to the request.
*
* <p>More info available here:
* https://developers.facebook.com/docs/reference/rest/fql.multiquery/
* </p>
*/
public class QueryNodeExtractor extends LaterWrapper<JsonNode, JsonNode>
{
Request<?> request;
/**
* @param multiqueryResult should be the graph selection of a MultiqueryRequest
*/
| public QueryNodeExtractor(Later<JsonNode> multiqueryResult) {
|
stickfigure/batchfb | src/test/java/com/googlecode/batchfb/test/MulitgraphTest.java | // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
| import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.googlecode.batchfb.Later;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Unit testing multiple graph calls batched together.
*
* @author Jeff Schnitzer
*/
public class MulitgraphTest extends TestBase {
/** */
static class Like {
public String id;
public String name;
}
/**
*/
@Test
public void multigraphAsNode() throws Exception {
| // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
// Path: src/test/java/com/googlecode/batchfb/test/MulitgraphTest.java
import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.googlecode.batchfb.Later;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Unit testing multiple graph calls batched together.
*
* @author Jeff Schnitzer
*/
public class MulitgraphTest extends TestBase {
/** */
static class Like {
public String id;
public String name;
}
/**
*/
@Test
public void multigraphAsNode() throws Exception {
| Later<JsonNode> mobcast = this.authBatcher.graph("157841729726");
|
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/GraphRequestBase.java | // Path: src/main/java/com/googlecode/batchfb/util/RequestBuilder.java
// public static enum HttpMethod {
// GET, POST, DELETE;
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/StringUtils.java
// public final class StringUtils
// {
// /**
// * Masks the useless checked exception from URLEncoder.encode()
// */
// public static String urlEncode(String string) {
// try {
// return URLEncoder.encode(string, "utf-8");
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException(e);
// }
// }
//
// /**
// * Masks the useless checked exception from URLDecoder.decode()
// */
// public static String urlDecode(String string) {
// try {
// return URLDecoder.decode(string, "utf-8");
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException(e);
// }
// }
//
//
// /**
// * Stringify the parameter value in an appropriate way. Note that Facebook fucks up dates by using unix time-since-epoch
// * some places and ISO-8601 others. However, maybe unix times always work as parameters?
// */
// public static String stringifyValue(Param param, ObjectMapper mapper) {
// assert !(param instanceof BinaryParam);
//
// if (param.value instanceof String)
// return (String)param.value;
// if (param.value instanceof Date)
// return Long.toString(((Date)param.value).getTime() / 1000);
// else if (param.value instanceof Number)
// return param.value.toString();
// else
// return JSONUtils.toJSON(param.value, mapper);
// }
//
// /**
// * Reads an input stream into a String, encoding with UTF-8
// */
// public static String read(InputStream input) {
// try {
// StringBuilder bld = new StringBuilder();
// Reader reader = new InputStreamReader(input, "utf-8");
// int ch;
// while ((ch = reader.read()) >= 0)
// bld.append((char)ch);
//
// return bld.toString();
// } catch (IOException ex) {
// throw new RuntimeException(ex);
// }
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.batchfb.util.RequestBuilder.HttpMethod;
import com.googlecode.batchfb.util.StringUtils; | package com.googlecode.batchfb;
/**
* <p>Common behavior for the requests that get batched at the top level.</p>
*
* <p>A little trick: This object is also serialized out to JSON as the array of batch parameters
* to the Facebook call. Its getters return the appropriate data.
*/
abstract public class GraphRequestBase<T> extends Request<T> {
private String object; | // Path: src/main/java/com/googlecode/batchfb/util/RequestBuilder.java
// public static enum HttpMethod {
// GET, POST, DELETE;
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/StringUtils.java
// public final class StringUtils
// {
// /**
// * Masks the useless checked exception from URLEncoder.encode()
// */
// public static String urlEncode(String string) {
// try {
// return URLEncoder.encode(string, "utf-8");
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException(e);
// }
// }
//
// /**
// * Masks the useless checked exception from URLDecoder.decode()
// */
// public static String urlDecode(String string) {
// try {
// return URLDecoder.decode(string, "utf-8");
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException(e);
// }
// }
//
//
// /**
// * Stringify the parameter value in an appropriate way. Note that Facebook fucks up dates by using unix time-since-epoch
// * some places and ISO-8601 others. However, maybe unix times always work as parameters?
// */
// public static String stringifyValue(Param param, ObjectMapper mapper) {
// assert !(param instanceof BinaryParam);
//
// if (param.value instanceof String)
// return (String)param.value;
// if (param.value instanceof Date)
// return Long.toString(((Date)param.value).getTime() / 1000);
// else if (param.value instanceof Number)
// return param.value.toString();
// else
// return JSONUtils.toJSON(param.value, mapper);
// }
//
// /**
// * Reads an input stream into a String, encoding with UTF-8
// */
// public static String read(InputStream input) {
// try {
// StringBuilder bld = new StringBuilder();
// Reader reader = new InputStreamReader(input, "utf-8");
// int ch;
// while ((ch = reader.read()) >= 0)
// bld.append((char)ch);
//
// return bld.toString();
// } catch (IOException ex) {
// throw new RuntimeException(ex);
// }
// }
// }
// Path: src/main/java/com/googlecode/batchfb/GraphRequestBase.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.batchfb.util.RequestBuilder.HttpMethod;
import com.googlecode.batchfb.util.StringUtils;
package com.googlecode.batchfb;
/**
* <p>Common behavior for the requests that get batched at the top level.</p>
*
* <p>A little trick: This object is also serialized out to JSON as the array of batch parameters
* to the Facebook call. Its getters return the appropriate data.
*/
abstract public class GraphRequestBase<T> extends Request<T> {
private String object; | private HttpMethod method; |
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/GraphRequestBase.java | // Path: src/main/java/com/googlecode/batchfb/util/RequestBuilder.java
// public static enum HttpMethod {
// GET, POST, DELETE;
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/StringUtils.java
// public final class StringUtils
// {
// /**
// * Masks the useless checked exception from URLEncoder.encode()
// */
// public static String urlEncode(String string) {
// try {
// return URLEncoder.encode(string, "utf-8");
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException(e);
// }
// }
//
// /**
// * Masks the useless checked exception from URLDecoder.decode()
// */
// public static String urlDecode(String string) {
// try {
// return URLDecoder.decode(string, "utf-8");
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException(e);
// }
// }
//
//
// /**
// * Stringify the parameter value in an appropriate way. Note that Facebook fucks up dates by using unix time-since-epoch
// * some places and ISO-8601 others. However, maybe unix times always work as parameters?
// */
// public static String stringifyValue(Param param, ObjectMapper mapper) {
// assert !(param instanceof BinaryParam);
//
// if (param.value instanceof String)
// return (String)param.value;
// if (param.value instanceof Date)
// return Long.toString(((Date)param.value).getTime() / 1000);
// else if (param.value instanceof Number)
// return param.value.toString();
// else
// return JSONUtils.toJSON(param.value, mapper);
// }
//
// /**
// * Reads an input stream into a String, encoding with UTF-8
// */
// public static String read(InputStream input) {
// try {
// StringBuilder bld = new StringBuilder();
// Reader reader = new InputStreamReader(input, "utf-8");
// int ch;
// while ((ch = reader.read()) >= 0)
// bld.append((char)ch);
//
// return bld.toString();
// } catch (IOException ex) {
// throw new RuntimeException(ex);
// }
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.batchfb.util.RequestBuilder.HttpMethod;
import com.googlecode.batchfb.util.StringUtils; | package com.googlecode.batchfb;
/**
* <p>Common behavior for the requests that get batched at the top level.</p>
*
* <p>A little trick: This object is also serialized out to JSON as the array of batch parameters
* to the Facebook call. Its getters return the appropriate data.
*/
abstract public class GraphRequestBase<T> extends Request<T> {
private String object;
private HttpMethod method;
/** This is an oddity because if missing it is by default true */
private Boolean omitResponseOnSuccess;
@JsonIgnore
protected ObjectMapper mapper;
/** Strips off any leading / from object */
public GraphRequestBase(String object, HttpMethod method, ObjectMapper mapper, Later<T> source) {
super(source);
this.object = object.startsWith("/") ? object.substring(1) : object;
this.method = method;
this.mapper = mapper;
}
/**
* Concrete subclasses should override this to provide params that will go into the construction of the relative url.
*/
abstract protected Param[] getParams();
/** Obnoxiously, if you don't set this false, the default is true */
public void setOmitResponseOnSuccess(boolean value) {
this.omitResponseOnSuccess = value;
}
/** If null, this property is true - silly facebook */
@JsonProperty("omit_response_on_success")
public Boolean getOmitResponseOnSuccess() {
return this.omitResponseOnSuccess;
}
/** Jackson does the right thing with this */
public HttpMethod getMethod() {
return this.method;
}
/** What Facebook uses to define the url in a batch */
@JsonProperty("relative_url")
public String getRelativeURL() {
StringBuilder bld = new StringBuilder();
bld.append(this.object);
Param[] params = this.getParams();
if (params != null && params.length > 0) {
bld.append('?');
boolean afterFirst = false;
for (Param param: params) {
if (afterFirst)
bld.append('&');
else
afterFirst = true;
if (param instanceof BinaryParam) {
//call.addParam(param.name, (InputStream)param.value, ((BinaryParam)param).contentType, "irrelevant");
throw new UnsupportedOperationException("Not quite sure what to do with BinaryParam yet");
} else { | // Path: src/main/java/com/googlecode/batchfb/util/RequestBuilder.java
// public static enum HttpMethod {
// GET, POST, DELETE;
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/StringUtils.java
// public final class StringUtils
// {
// /**
// * Masks the useless checked exception from URLEncoder.encode()
// */
// public static String urlEncode(String string) {
// try {
// return URLEncoder.encode(string, "utf-8");
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException(e);
// }
// }
//
// /**
// * Masks the useless checked exception from URLDecoder.decode()
// */
// public static String urlDecode(String string) {
// try {
// return URLDecoder.decode(string, "utf-8");
// } catch (UnsupportedEncodingException e) {
// throw new RuntimeException(e);
// }
// }
//
//
// /**
// * Stringify the parameter value in an appropriate way. Note that Facebook fucks up dates by using unix time-since-epoch
// * some places and ISO-8601 others. However, maybe unix times always work as parameters?
// */
// public static String stringifyValue(Param param, ObjectMapper mapper) {
// assert !(param instanceof BinaryParam);
//
// if (param.value instanceof String)
// return (String)param.value;
// if (param.value instanceof Date)
// return Long.toString(((Date)param.value).getTime() / 1000);
// else if (param.value instanceof Number)
// return param.value.toString();
// else
// return JSONUtils.toJSON(param.value, mapper);
// }
//
// /**
// * Reads an input stream into a String, encoding with UTF-8
// */
// public static String read(InputStream input) {
// try {
// StringBuilder bld = new StringBuilder();
// Reader reader = new InputStreamReader(input, "utf-8");
// int ch;
// while ((ch = reader.read()) >= 0)
// bld.append((char)ch);
//
// return bld.toString();
// } catch (IOException ex) {
// throw new RuntimeException(ex);
// }
// }
// }
// Path: src/main/java/com/googlecode/batchfb/GraphRequestBase.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.batchfb.util.RequestBuilder.HttpMethod;
import com.googlecode.batchfb.util.StringUtils;
package com.googlecode.batchfb;
/**
* <p>Common behavior for the requests that get batched at the top level.</p>
*
* <p>A little trick: This object is also serialized out to JSON as the array of batch parameters
* to the Facebook call. Its getters return the appropriate data.
*/
abstract public class GraphRequestBase<T> extends Request<T> {
private String object;
private HttpMethod method;
/** This is an oddity because if missing it is by default true */
private Boolean omitResponseOnSuccess;
@JsonIgnore
protected ObjectMapper mapper;
/** Strips off any leading / from object */
public GraphRequestBase(String object, HttpMethod method, ObjectMapper mapper, Later<T> source) {
super(source);
this.object = object.startsWith("/") ? object.substring(1) : object;
this.method = method;
this.mapper = mapper;
}
/**
* Concrete subclasses should override this to provide params that will go into the construction of the relative url.
*/
abstract protected Param[] getParams();
/** Obnoxiously, if you don't set this false, the default is true */
public void setOmitResponseOnSuccess(boolean value) {
this.omitResponseOnSuccess = value;
}
/** If null, this property is true - silly facebook */
@JsonProperty("omit_response_on_success")
public Boolean getOmitResponseOnSuccess() {
return this.omitResponseOnSuccess;
}
/** Jackson does the right thing with this */
public HttpMethod getMethod() {
return this.method;
}
/** What Facebook uses to define the url in a batch */
@JsonProperty("relative_url")
public String getRelativeURL() {
StringBuilder bld = new StringBuilder();
bld.append(this.object);
Param[] params = this.getParams();
if (params != null && params.length > 0) {
bld.append('?');
boolean afterFirst = false;
for (Param param: params) {
if (afterFirst)
bld.append('&');
else
afterFirst = true;
if (param instanceof BinaryParam) {
//call.addParam(param.name, (InputStream)param.value, ((BinaryParam)param).contentType, "irrelevant");
throw new UnsupportedOperationException("Not quite sure what to do with BinaryParam yet");
} else { | String paramValue = StringUtils.stringifyValue(param, this.mapper); |
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/impl/GraphNodeExtractor.java | // Path: src/main/java/com/googlecode/batchfb/err/BrokenFacebookException.java
// public class BrokenFacebookException extends FacebookException {
// private static final long serialVersionUID = 1L;
//
// /** Make GWT happy */
// BrokenFacebookException() {}
//
// public BrokenFacebookException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/JSONUtils.java
// public class JSONUtils {
//
// /**
// * Converts the object to a JSON string using the mapper
// */
// public static String toJSON(Object value, ObjectMapper mapper) {
// try {
// return mapper.writeValueAsString(value);
// } catch (IOException ex) {
// throw new FacebookException(ex);
// }
// }
//
// /**
// * Parses a string into a JsonNode using the mapper
// */
// public static JsonNode toNode(String value, ObjectMapper mapper) {
// try {
// return mapper.readTree(value);
// } catch (IOException ex) {
// throw new FacebookException(ex);
// }
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/LaterWrapper.java
// public class LaterWrapper<K, V> implements Later<V>
// {
// private Later<K> orig;
// private V cached;
//
// public LaterWrapper(Later<K> orig)
// {
// this.orig = orig;
// }
//
// @Override
// public V get() throws FacebookException
// {
// if (this.cached == null)
// this.cached = this.convert(this.orig.get());
//
// return this.cached;
// }
//
// /** Override this; default is just to pass through which will be unsafe if types are incompatible */
// @SuppressWarnings("unchecked")
// protected V convert(K data)
// {
// return (V)data;
// }
// }
| import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.err.BrokenFacebookException;
import com.googlecode.batchfb.util.JSONUtils;
import com.googlecode.batchfb.util.LaterWrapper;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.impl;
/**
* <p>Knows how to get the JsonNode for a particular graph request out of a batchResult.
* The batchResult must look like the result described here:
* https://developers.facebook.com/docs/api/batch/</p>
*/
public class GraphNodeExtractor extends LaterWrapper<JsonNode, JsonNode>
{
int index;
ObjectMapper mapper;
/** Force the input to be error detected so we always have a valid input */
public GraphNodeExtractor(int index, ObjectMapper mapper, ErrorDetectingWrapper batchResult)
{
super(batchResult);
this.index = index;
this.mapper = mapper;
}
/** */
@Override
protected JsonNode convert(JsonNode data)
{
if (!(data instanceof ArrayNode))
throw new IllegalStateException("Expected array node: " + data);
JsonNode batchPart = ((ArrayNode)data).get(this.index);
if (batchPart == null || batchPart.isNull())
| // Path: src/main/java/com/googlecode/batchfb/err/BrokenFacebookException.java
// public class BrokenFacebookException extends FacebookException {
// private static final long serialVersionUID = 1L;
//
// /** Make GWT happy */
// BrokenFacebookException() {}
//
// public BrokenFacebookException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/JSONUtils.java
// public class JSONUtils {
//
// /**
// * Converts the object to a JSON string using the mapper
// */
// public static String toJSON(Object value, ObjectMapper mapper) {
// try {
// return mapper.writeValueAsString(value);
// } catch (IOException ex) {
// throw new FacebookException(ex);
// }
// }
//
// /**
// * Parses a string into a JsonNode using the mapper
// */
// public static JsonNode toNode(String value, ObjectMapper mapper) {
// try {
// return mapper.readTree(value);
// } catch (IOException ex) {
// throw new FacebookException(ex);
// }
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/LaterWrapper.java
// public class LaterWrapper<K, V> implements Later<V>
// {
// private Later<K> orig;
// private V cached;
//
// public LaterWrapper(Later<K> orig)
// {
// this.orig = orig;
// }
//
// @Override
// public V get() throws FacebookException
// {
// if (this.cached == null)
// this.cached = this.convert(this.orig.get());
//
// return this.cached;
// }
//
// /** Override this; default is just to pass through which will be unsafe if types are incompatible */
// @SuppressWarnings("unchecked")
// protected V convert(K data)
// {
// return (V)data;
// }
// }
// Path: src/main/java/com/googlecode/batchfb/impl/GraphNodeExtractor.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.err.BrokenFacebookException;
import com.googlecode.batchfb.util.JSONUtils;
import com.googlecode.batchfb.util.LaterWrapper;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.impl;
/**
* <p>Knows how to get the JsonNode for a particular graph request out of a batchResult.
* The batchResult must look like the result described here:
* https://developers.facebook.com/docs/api/batch/</p>
*/
public class GraphNodeExtractor extends LaterWrapper<JsonNode, JsonNode>
{
int index;
ObjectMapper mapper;
/** Force the input to be error detected so we always have a valid input */
public GraphNodeExtractor(int index, ObjectMapper mapper, ErrorDetectingWrapper batchResult)
{
super(batchResult);
this.index = index;
this.mapper = mapper;
}
/** */
@Override
protected JsonNode convert(JsonNode data)
{
if (!(data instanceof ArrayNode))
throw new IllegalStateException("Expected array node: " + data);
JsonNode batchPart = ((ArrayNode)data).get(this.index);
if (batchPart == null || batchPart.isNull())
| throw new BrokenFacebookException("Facebook returned an invalid batch response. There should not be a null at index " + index + " of this array: " + data);
|
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/impl/GraphNodeExtractor.java | // Path: src/main/java/com/googlecode/batchfb/err/BrokenFacebookException.java
// public class BrokenFacebookException extends FacebookException {
// private static final long serialVersionUID = 1L;
//
// /** Make GWT happy */
// BrokenFacebookException() {}
//
// public BrokenFacebookException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/JSONUtils.java
// public class JSONUtils {
//
// /**
// * Converts the object to a JSON string using the mapper
// */
// public static String toJSON(Object value, ObjectMapper mapper) {
// try {
// return mapper.writeValueAsString(value);
// } catch (IOException ex) {
// throw new FacebookException(ex);
// }
// }
//
// /**
// * Parses a string into a JsonNode using the mapper
// */
// public static JsonNode toNode(String value, ObjectMapper mapper) {
// try {
// return mapper.readTree(value);
// } catch (IOException ex) {
// throw new FacebookException(ex);
// }
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/LaterWrapper.java
// public class LaterWrapper<K, V> implements Later<V>
// {
// private Later<K> orig;
// private V cached;
//
// public LaterWrapper(Later<K> orig)
// {
// this.orig = orig;
// }
//
// @Override
// public V get() throws FacebookException
// {
// if (this.cached == null)
// this.cached = this.convert(this.orig.get());
//
// return this.cached;
// }
//
// /** Override this; default is just to pass through which will be unsafe if types are incompatible */
// @SuppressWarnings("unchecked")
// protected V convert(K data)
// {
// return (V)data;
// }
// }
| import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.err.BrokenFacebookException;
import com.googlecode.batchfb.util.JSONUtils;
import com.googlecode.batchfb.util.LaterWrapper;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.impl;
/**
* <p>Knows how to get the JsonNode for a particular graph request out of a batchResult.
* The batchResult must look like the result described here:
* https://developers.facebook.com/docs/api/batch/</p>
*/
public class GraphNodeExtractor extends LaterWrapper<JsonNode, JsonNode>
{
int index;
ObjectMapper mapper;
/** Force the input to be error detected so we always have a valid input */
public GraphNodeExtractor(int index, ObjectMapper mapper, ErrorDetectingWrapper batchResult)
{
super(batchResult);
this.index = index;
this.mapper = mapper;
}
/** */
@Override
protected JsonNode convert(JsonNode data)
{
if (!(data instanceof ArrayNode))
throw new IllegalStateException("Expected array node: " + data);
JsonNode batchPart = ((ArrayNode)data).get(this.index);
if (batchPart == null || batchPart.isNull())
throw new BrokenFacebookException("Facebook returned an invalid batch response. There should not be a null at index " + index + " of this array: " + data);
// This should be something like:
// {
// "code": 200,
// "headers": [ { "name":"Content-Type", "value":"text/javascript; charset=UTF-8" } ],
// "body":"{\"id\":\"asdf\"}"
// },
JsonNode body = batchPart.get("body");
if (body == null || body.isNull())
return null;
else
| // Path: src/main/java/com/googlecode/batchfb/err/BrokenFacebookException.java
// public class BrokenFacebookException extends FacebookException {
// private static final long serialVersionUID = 1L;
//
// /** Make GWT happy */
// BrokenFacebookException() {}
//
// public BrokenFacebookException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/JSONUtils.java
// public class JSONUtils {
//
// /**
// * Converts the object to a JSON string using the mapper
// */
// public static String toJSON(Object value, ObjectMapper mapper) {
// try {
// return mapper.writeValueAsString(value);
// } catch (IOException ex) {
// throw new FacebookException(ex);
// }
// }
//
// /**
// * Parses a string into a JsonNode using the mapper
// */
// public static JsonNode toNode(String value, ObjectMapper mapper) {
// try {
// return mapper.readTree(value);
// } catch (IOException ex) {
// throw new FacebookException(ex);
// }
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/util/LaterWrapper.java
// public class LaterWrapper<K, V> implements Later<V>
// {
// private Later<K> orig;
// private V cached;
//
// public LaterWrapper(Later<K> orig)
// {
// this.orig = orig;
// }
//
// @Override
// public V get() throws FacebookException
// {
// if (this.cached == null)
// this.cached = this.convert(this.orig.get());
//
// return this.cached;
// }
//
// /** Override this; default is just to pass through which will be unsafe if types are incompatible */
// @SuppressWarnings("unchecked")
// protected V convert(K data)
// {
// return (V)data;
// }
// }
// Path: src/main/java/com/googlecode/batchfb/impl/GraphNodeExtractor.java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.googlecode.batchfb.err.BrokenFacebookException;
import com.googlecode.batchfb.util.JSONUtils;
import com.googlecode.batchfb.util.LaterWrapper;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.impl;
/**
* <p>Knows how to get the JsonNode for a particular graph request out of a batchResult.
* The batchResult must look like the result described here:
* https://developers.facebook.com/docs/api/batch/</p>
*/
public class GraphNodeExtractor extends LaterWrapper<JsonNode, JsonNode>
{
int index;
ObjectMapper mapper;
/** Force the input to be error detected so we always have a valid input */
public GraphNodeExtractor(int index, ObjectMapper mapper, ErrorDetectingWrapper batchResult)
{
super(batchResult);
this.index = index;
this.mapper = mapper;
}
/** */
@Override
protected JsonNode convert(JsonNode data)
{
if (!(data instanceof ArrayNode))
throw new IllegalStateException("Expected array node: " + data);
JsonNode batchPart = ((ArrayNode)data).get(this.index);
if (batchPart == null || batchPart.isNull())
throw new BrokenFacebookException("Facebook returned an invalid batch response. There should not be a null at index " + index + " of this array: " + data);
// This should be something like:
// {
// "code": 200,
// "headers": [ { "name":"Content-Type", "value":"text/javascript; charset=UTF-8" } ],
// "body":"{\"id\":\"asdf\"}"
// },
JsonNode body = batchPart.get("body");
if (body == null || body.isNull())
return null;
else
| return JSONUtils.toNode(body.textValue(), mapper);
|
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/util/StringUtils.java | // Path: src/main/java/com/googlecode/batchfb/BinaryParam.java
// public class BinaryParam extends Param {
//
// public final String contentType;
//
// /**
// */
// public BinaryParam(String name, InputStream value, String contentType) {
// super(name, value);
// this.contentType = contentType;
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, contentType);
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Param.java
// public class Param {
//
// /** */
// public final String name;
//
// /** Will be turned into a string (possibly json-mapped) later */
// public final Object value;
//
// /**
// * @param value must be something that can be converted to a String with toString().
// */
// public Param(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * @return a version useful for debugging.
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, value);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.batchfb.BinaryParam;
import com.googlecode.batchfb.Param;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.util;
/**
* Some string handling utilities
*/
public final class StringUtils
{
/**
* Masks the useless checked exception from URLEncoder.encode()
*/
public static String urlEncode(String string) {
try {
return URLEncoder.encode(string, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Masks the useless checked exception from URLDecoder.decode()
*/
public static String urlDecode(String string) {
try {
return URLDecoder.decode(string, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Stringify the parameter value in an appropriate way. Note that Facebook fucks up dates by using unix time-since-epoch
* some places and ISO-8601 others. However, maybe unix times always work as parameters?
*/
| // Path: src/main/java/com/googlecode/batchfb/BinaryParam.java
// public class BinaryParam extends Param {
//
// public final String contentType;
//
// /**
// */
// public BinaryParam(String name, InputStream value, String contentType) {
// super(name, value);
// this.contentType = contentType;
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, contentType);
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Param.java
// public class Param {
//
// /** */
// public final String name;
//
// /** Will be turned into a string (possibly json-mapped) later */
// public final Object value;
//
// /**
// * @param value must be something that can be converted to a String with toString().
// */
// public Param(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * @return a version useful for debugging.
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, value);
// }
// }
// Path: src/main/java/com/googlecode/batchfb/util/StringUtils.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.batchfb.BinaryParam;
import com.googlecode.batchfb.Param;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.util;
/**
* Some string handling utilities
*/
public final class StringUtils
{
/**
* Masks the useless checked exception from URLEncoder.encode()
*/
public static String urlEncode(String string) {
try {
return URLEncoder.encode(string, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Masks the useless checked exception from URLDecoder.decode()
*/
public static String urlDecode(String string) {
try {
return URLDecoder.decode(string, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Stringify the parameter value in an appropriate way. Note that Facebook fucks up dates by using unix time-since-epoch
* some places and ISO-8601 others. However, maybe unix times always work as parameters?
*/
| public static String stringifyValue(Param param, ObjectMapper mapper) {
|
stickfigure/batchfb | src/main/java/com/googlecode/batchfb/util/StringUtils.java | // Path: src/main/java/com/googlecode/batchfb/BinaryParam.java
// public class BinaryParam extends Param {
//
// public final String contentType;
//
// /**
// */
// public BinaryParam(String name, InputStream value, String contentType) {
// super(name, value);
// this.contentType = contentType;
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, contentType);
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Param.java
// public class Param {
//
// /** */
// public final String name;
//
// /** Will be turned into a string (possibly json-mapped) later */
// public final Object value;
//
// /**
// * @param value must be something that can be converted to a String with toString().
// */
// public Param(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * @return a version useful for debugging.
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, value);
// }
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.batchfb.BinaryParam;
import com.googlecode.batchfb.Param;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.util;
/**
* Some string handling utilities
*/
public final class StringUtils
{
/**
* Masks the useless checked exception from URLEncoder.encode()
*/
public static String urlEncode(String string) {
try {
return URLEncoder.encode(string, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Masks the useless checked exception from URLDecoder.decode()
*/
public static String urlDecode(String string) {
try {
return URLDecoder.decode(string, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Stringify the parameter value in an appropriate way. Note that Facebook fucks up dates by using unix time-since-epoch
* some places and ISO-8601 others. However, maybe unix times always work as parameters?
*/
public static String stringifyValue(Param param, ObjectMapper mapper) {
| // Path: src/main/java/com/googlecode/batchfb/BinaryParam.java
// public class BinaryParam extends Param {
//
// public final String contentType;
//
// /**
// */
// public BinaryParam(String name, InputStream value, String contentType) {
// super(name, value);
// this.contentType = contentType;
// }
//
// /**
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, contentType);
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Param.java
// public class Param {
//
// /** */
// public final String name;
//
// /** Will be turned into a string (possibly json-mapped) later */
// public final Object value;
//
// /**
// * @param value must be something that can be converted to a String with toString().
// */
// public Param(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * @return a version useful for debugging.
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, value);
// }
// }
// Path: src/main/java/com/googlecode/batchfb/util/StringUtils.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.googlecode.batchfb.BinaryParam;
import com.googlecode.batchfb.Param;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.util;
/**
* Some string handling utilities
*/
public final class StringUtils
{
/**
* Masks the useless checked exception from URLEncoder.encode()
*/
public static String urlEncode(String string) {
try {
return URLEncoder.encode(string, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Masks the useless checked exception from URLDecoder.decode()
*/
public static String urlDecode(String string) {
try {
return URLDecoder.decode(string, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Stringify the parameter value in an appropriate way. Note that Facebook fucks up dates by using unix time-since-epoch
* some places and ISO-8601 others. However, maybe unix times always work as parameters?
*/
public static String stringifyValue(Param param, ObjectMapper mapper) {
| assert !(param instanceof BinaryParam);
|
stickfigure/batchfb | src/test/java/com/googlecode/batchfb/test/PagedTest.java | // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/PagedLater.java
// public interface PagedLater<T> extends Later<List<T>> {
//
// /**
// * Executes the current batch (if necessary) and enqueues a request for the previous page of data.
// * If there is no previous page of data, this method will return null.
// *
// * @throws FacebookException if there was an error executing the original request.
// */
// PagedLater<T> previous() throws FacebookException;
//
// /**
// * Executes the current batch (if necessary) and enqueues a request for the next page of data.
// * If there is no next page of data, this method will return null.
// *
// * @throws FacebookException if there was an error executing the original request.
// */
// PagedLater<T> next() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/Param.java
// public class Param {
//
// /** */
// public final String name;
//
// /** Will be turned into a string (possibly json-mapped) later */
// public final Object value;
//
// /**
// * @param value must be something that can be converted to a String with toString().
// */
// public Param(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * @return a version useful for debugging.
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, value);
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/type/Paged.java
// public class Paged<T> {
//
// public static class Paging {
// String previous;
// public String getPrevious() { return this.previous; }
// public void setPrevious(String value) { this.previous = value; }
//
// String next;
// public String getNext() { return this.next; }
// public void setNext(String value) { this.next = value; }
// }
//
// List<T> data;
// public List<T> getData() { return this.data; }
// public void setData(List<T> value) { this.data = value; }
//
// Paging paging;
// public Paging getPaging() { return this.paging; }
// public void setPaging(Paging value) { this.paging = value; }
// }
| import com.googlecode.batchfb.Param;
import com.googlecode.batchfb.type.Paged;
import java.util.Date;
import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.PagedLater;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Testing out connections (paged stuff). Note that these require an auth token
* for an account that has a lot of stuff in the stream.
*
* @author Jeff Schnitzer
*/
public class PagedTest extends TestBase
{
/**
* Tests using the normal graph() call to get paged data. Expects to find
* stuff on your home.
*/
@Test
public void simpleRawPaged() throws Exception {
| // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/PagedLater.java
// public interface PagedLater<T> extends Later<List<T>> {
//
// /**
// * Executes the current batch (if necessary) and enqueues a request for the previous page of data.
// * If there is no previous page of data, this method will return null.
// *
// * @throws FacebookException if there was an error executing the original request.
// */
// PagedLater<T> previous() throws FacebookException;
//
// /**
// * Executes the current batch (if necessary) and enqueues a request for the next page of data.
// * If there is no next page of data, this method will return null.
// *
// * @throws FacebookException if there was an error executing the original request.
// */
// PagedLater<T> next() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/Param.java
// public class Param {
//
// /** */
// public final String name;
//
// /** Will be turned into a string (possibly json-mapped) later */
// public final Object value;
//
// /**
// * @param value must be something that can be converted to a String with toString().
// */
// public Param(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * @return a version useful for debugging.
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, value);
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/type/Paged.java
// public class Paged<T> {
//
// public static class Paging {
// String previous;
// public String getPrevious() { return this.previous; }
// public void setPrevious(String value) { this.previous = value; }
//
// String next;
// public String getNext() { return this.next; }
// public void setNext(String value) { this.next = value; }
// }
//
// List<T> data;
// public List<T> getData() { return this.data; }
// public void setData(List<T> value) { this.data = value; }
//
// Paging paging;
// public Paging getPaging() { return this.paging; }
// public void setPaging(Paging value) { this.paging = value; }
// }
// Path: src/test/java/com/googlecode/batchfb/test/PagedTest.java
import com.googlecode.batchfb.Param;
import com.googlecode.batchfb.type.Paged;
import java.util.Date;
import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.PagedLater;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Testing out connections (paged stuff). Note that these require an auth token
* for an account that has a lot of stuff in the stream.
*
* @author Jeff Schnitzer
*/
public class PagedTest extends TestBase
{
/**
* Tests using the normal graph() call to get paged data. Expects to find
* stuff on your home.
*/
@Test
public void simpleRawPaged() throws Exception {
| Later<Paged<Object>> feed = this.authBatcher.graph("me/home", new TypeReference<Paged<Object>>(){});
|
stickfigure/batchfb | src/test/java/com/googlecode/batchfb/test/PagedTest.java | // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/PagedLater.java
// public interface PagedLater<T> extends Later<List<T>> {
//
// /**
// * Executes the current batch (if necessary) and enqueues a request for the previous page of data.
// * If there is no previous page of data, this method will return null.
// *
// * @throws FacebookException if there was an error executing the original request.
// */
// PagedLater<T> previous() throws FacebookException;
//
// /**
// * Executes the current batch (if necessary) and enqueues a request for the next page of data.
// * If there is no next page of data, this method will return null.
// *
// * @throws FacebookException if there was an error executing the original request.
// */
// PagedLater<T> next() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/Param.java
// public class Param {
//
// /** */
// public final String name;
//
// /** Will be turned into a string (possibly json-mapped) later */
// public final Object value;
//
// /**
// * @param value must be something that can be converted to a String with toString().
// */
// public Param(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * @return a version useful for debugging.
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, value);
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/type/Paged.java
// public class Paged<T> {
//
// public static class Paging {
// String previous;
// public String getPrevious() { return this.previous; }
// public void setPrevious(String value) { this.previous = value; }
//
// String next;
// public String getNext() { return this.next; }
// public void setNext(String value) { this.next = value; }
// }
//
// List<T> data;
// public List<T> getData() { return this.data; }
// public void setData(List<T> value) { this.data = value; }
//
// Paging paging;
// public Paging getPaging() { return this.paging; }
// public void setPaging(Paging value) { this.paging = value; }
// }
| import com.googlecode.batchfb.Param;
import com.googlecode.batchfb.type.Paged;
import java.util.Date;
import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.PagedLater;
| /*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Testing out connections (paged stuff). Note that these require an auth token
* for an account that has a lot of stuff in the stream.
*
* @author Jeff Schnitzer
*/
public class PagedTest extends TestBase
{
/**
* Tests using the normal graph() call to get paged data. Expects to find
* stuff on your home.
*/
@Test
public void simpleRawPaged() throws Exception {
| // Path: src/test/java/com/googlecode/batchfb/test/util/TestBase.java
// public class TestBase {
//
// /** This should be set on the command line with a -DaccessToken=BLAH argument */
// protected static final String ACCESS_TOKEN = System.getProperty("accessToken", "");
//
// /** */
// protected Batcher authBatcher;
//
// @BeforeMethod
// public void setUp() throws Exception {
// this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
// }
//
// @AfterMethod
// public void tearDown() throws Exception {
// this.authBatcher = null;
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/Later.java
// public interface Later<T> {
// /**
// * <p>Get the value, triggering execution of the batch if necessary. Once the batch
// * has been executed, this method can be called repeatedly without incurring further
// * calls to Facebook or triggering the execution of any subsequently created batches.
// * It is as efficient as a simple value getter.</p>
// *
// * <p>If the Facebook call produced an error, repeated calls to this method will produce
// * the same exception. BatchFB will *not* retry a Facebook call; you must create a
// * new Later<?> object from the FacebookBatcher class.</p>
// *
// * @throws FacebookException if anything went wrong with the Facebook interaction
// */
// T get() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/PagedLater.java
// public interface PagedLater<T> extends Later<List<T>> {
//
// /**
// * Executes the current batch (if necessary) and enqueues a request for the previous page of data.
// * If there is no previous page of data, this method will return null.
// *
// * @throws FacebookException if there was an error executing the original request.
// */
// PagedLater<T> previous() throws FacebookException;
//
// /**
// * Executes the current batch (if necessary) and enqueues a request for the next page of data.
// * If there is no next page of data, this method will return null.
// *
// * @throws FacebookException if there was an error executing the original request.
// */
// PagedLater<T> next() throws FacebookException;
// }
//
// Path: src/main/java/com/googlecode/batchfb/Param.java
// public class Param {
//
// /** */
// public final String name;
//
// /** Will be turned into a string (possibly json-mapped) later */
// public final Object value;
//
// /**
// * @param value must be something that can be converted to a String with toString().
// */
// public Param(String name, Object value) {
// this.name = name;
// this.value = value;
// }
//
// /**
// * @return a version useful for debugging.
// */
// @Override
// public String toString() {
// return String.format("%s[%s=%s]", this.getClass().getName(), name, value);
// }
// }
//
// Path: src/main/java/com/googlecode/batchfb/type/Paged.java
// public class Paged<T> {
//
// public static class Paging {
// String previous;
// public String getPrevious() { return this.previous; }
// public void setPrevious(String value) { this.previous = value; }
//
// String next;
// public String getNext() { return this.next; }
// public void setNext(String value) { this.next = value; }
// }
//
// List<T> data;
// public List<T> getData() { return this.data; }
// public void setData(List<T> value) { this.data = value; }
//
// Paging paging;
// public Paging getPaging() { return this.paging; }
// public void setPaging(Paging value) { this.paging = value; }
// }
// Path: src/test/java/com/googlecode/batchfb/test/PagedTest.java
import com.googlecode.batchfb.Param;
import com.googlecode.batchfb.type.Paged;
import java.util.Date;
import com.googlecode.batchfb.test.util.TestBase;
import org.testng.annotations.Test;
import com.fasterxml.jackson.core.type.TypeReference;
import com.googlecode.batchfb.Later;
import com.googlecode.batchfb.PagedLater;
/*
* Copyright (c) 2010 Jeff Schnitzer.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.googlecode.batchfb.test;
/**
* Testing out connections (paged stuff). Note that these require an auth token
* for an account that has a lot of stuff in the stream.
*
* @author Jeff Schnitzer
*/
public class PagedTest extends TestBase
{
/**
* Tests using the normal graph() call to get paged data. Expects to find
* stuff on your home.
*/
@Test
public void simpleRawPaged() throws Exception {
| Later<Paged<Object>> feed = this.authBatcher.graph("me/home", new TypeReference<Paged<Object>>(){});
|
szegedi/dynalink | src/test/java_inactive/DynamicDispatchDemo.java | // Path: src/main/java/org/dynalang/dynalink/MonomorphicCallSite.java
// public class MonomorphicCallSite extends AbstractRelinkableCallSite {
// /**
// * Creates a new call site with monomorphic inline caching strategy.
// * @param descriptor the descriptor for this call site
// */
// public MonomorphicCallSite(final CallSiteDescriptor descriptor) {
// super(descriptor);
// }
//
// @Override
// public void relink(final GuardedInvocation guardedInvocation, final MethodHandle relink) {
// setTarget(guardedInvocation.compose(relink));
// }
//
// @Override
// public void resetAndRelink(final GuardedInvocation guardedInvocation, final MethodHandle relink) {
// relink(guardedInvocation, relink);
// }
// }
//
// Path: src/main/java/org/dynalang/dynalink/RelinkableCallSite.java
// public interface RelinkableCallSite {
// /**
// * Initializes the relinkable call site by setting a relink-and-invoke method handle. The call site implementation
// * is supposed to set this method handle as its target.
// * @param relinkAndInvoke a relink-and-invoke method handle supplied by the {@link DynamicLinker}.
// */
// public void initialize(MethodHandle relinkAndInvoke);
//
// /**
// * Returns the descriptor for this call site.
// *
// * @return the descriptor for this call site.
// */
// public CallSiteDescriptor getDescriptor();
//
// /**
// * This method will be called by the dynamic linker every time the call site is normally relinked. It will be passed
// * a {@code GuardedInvocation} that the call site should incorporate into its target method handle. When this method
// * is called, the call site is allowed to keep other non-invalidated invocations around for implementation of
// * polymorphic inline caches and compose them with this invocation to form its final target.
// *
// * @param guardedInvocation the guarded invocation that the call site should incorporate into its target method
// * handle.
// * @param fallback the fallback method. This is a method matching the method type of the call site that is supplied
// * by the {@link DynamicLinker} to be used by this call site as a fallback when it can't invoke its target with the
// * passed arguments. The fallback method is such that when it's invoked, it'll try to discover the adequate target
// * for the invocation, subsequently invoke {@link #relink(GuardedInvocation, MethodHandle)} or
// * {@link #resetAndRelink(GuardedInvocation, MethodHandle)}, and finally invoke the target.
// */
// public void relink(GuardedInvocation guardedInvocation, MethodHandle fallback);
//
// /**
// * This method will be called by the dynamic linker every time the call site is relinked and the linker wishes the
// * call site to throw away any prior linkage state. It will be passed a {@code GuardedInvocation} that the call site
// * should use to build its target method handle. When this method is called, the call site is discouraged from
// * keeping previous state around, and is supposed to only link the current invocation.
// *
// * @param guardedInvocation the guarded invocation that the call site should use to build its target method handle.
// * @param fallback the fallback method. This is a method matching the method type of the call site that is supplied
// * by the {@link DynamicLinker} to be used by this call site as a fallback when it can't invoke its target with the
// * passed arguments. The fallback method is such that when it's invoked, it'll try to discover the adequate target
// * for the invocation, subsequently invoke {@link #relink(GuardedInvocation, MethodHandle)} or
// * {@link #resetAndRelink(GuardedInvocation, MethodHandle)}, and finally invoke the target.
// */
// public void resetAndRelink(GuardedInvocation guardedInvocation, MethodHandle fallback);
// }
| import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import org.dynalang.dynalink.MonomorphicCallSite;
import org.dynalang.dynalink.RelinkableCallSite;
import org.dynalang.dynalink.linker.CallSiteDescriptor; |
public class DynamicDispatchDemo {
public static class English {
public void sayHello() {
System.out.println("Hello!");
}
}
public static class Spanish {
public void sayHello() {
System.out.println("Hola!");
}
}
public static void main(String[] args) throws Throwable {
final Object[] greeters =
new Object[] { new English(), new Spanish(), new English(),
new Spanish(), new Spanish(), new English(),
new English() };
final MethodHandle sayHelloInvoker =
new DynamicIndy().invokeDynamic("sayHello", MethodType
.methodType(Void.TYPE), DynamicDispatchDemo.class,
"bootstrap", MethodType.methodType(CallSite.class,
MethodHandles.Lookup.class, String.class,
MethodType.class));
for(Object greeter: greeters) {
sayHelloInvoker.invokeGeneric(greeter);
}
}
public static CallSite bootstrap(MethodHandles.Lookup lookup, String name,
MethodType callSiteType) { | // Path: src/main/java/org/dynalang/dynalink/MonomorphicCallSite.java
// public class MonomorphicCallSite extends AbstractRelinkableCallSite {
// /**
// * Creates a new call site with monomorphic inline caching strategy.
// * @param descriptor the descriptor for this call site
// */
// public MonomorphicCallSite(final CallSiteDescriptor descriptor) {
// super(descriptor);
// }
//
// @Override
// public void relink(final GuardedInvocation guardedInvocation, final MethodHandle relink) {
// setTarget(guardedInvocation.compose(relink));
// }
//
// @Override
// public void resetAndRelink(final GuardedInvocation guardedInvocation, final MethodHandle relink) {
// relink(guardedInvocation, relink);
// }
// }
//
// Path: src/main/java/org/dynalang/dynalink/RelinkableCallSite.java
// public interface RelinkableCallSite {
// /**
// * Initializes the relinkable call site by setting a relink-and-invoke method handle. The call site implementation
// * is supposed to set this method handle as its target.
// * @param relinkAndInvoke a relink-and-invoke method handle supplied by the {@link DynamicLinker}.
// */
// public void initialize(MethodHandle relinkAndInvoke);
//
// /**
// * Returns the descriptor for this call site.
// *
// * @return the descriptor for this call site.
// */
// public CallSiteDescriptor getDescriptor();
//
// /**
// * This method will be called by the dynamic linker every time the call site is normally relinked. It will be passed
// * a {@code GuardedInvocation} that the call site should incorporate into its target method handle. When this method
// * is called, the call site is allowed to keep other non-invalidated invocations around for implementation of
// * polymorphic inline caches and compose them with this invocation to form its final target.
// *
// * @param guardedInvocation the guarded invocation that the call site should incorporate into its target method
// * handle.
// * @param fallback the fallback method. This is a method matching the method type of the call site that is supplied
// * by the {@link DynamicLinker} to be used by this call site as a fallback when it can't invoke its target with the
// * passed arguments. The fallback method is such that when it's invoked, it'll try to discover the adequate target
// * for the invocation, subsequently invoke {@link #relink(GuardedInvocation, MethodHandle)} or
// * {@link #resetAndRelink(GuardedInvocation, MethodHandle)}, and finally invoke the target.
// */
// public void relink(GuardedInvocation guardedInvocation, MethodHandle fallback);
//
// /**
// * This method will be called by the dynamic linker every time the call site is relinked and the linker wishes the
// * call site to throw away any prior linkage state. It will be passed a {@code GuardedInvocation} that the call site
// * should use to build its target method handle. When this method is called, the call site is discouraged from
// * keeping previous state around, and is supposed to only link the current invocation.
// *
// * @param guardedInvocation the guarded invocation that the call site should use to build its target method handle.
// * @param fallback the fallback method. This is a method matching the method type of the call site that is supplied
// * by the {@link DynamicLinker} to be used by this call site as a fallback when it can't invoke its target with the
// * passed arguments. The fallback method is such that when it's invoked, it'll try to discover the adequate target
// * for the invocation, subsequently invoke {@link #relink(GuardedInvocation, MethodHandle)} or
// * {@link #resetAndRelink(GuardedInvocation, MethodHandle)}, and finally invoke the target.
// */
// public void resetAndRelink(GuardedInvocation guardedInvocation, MethodHandle fallback);
// }
// Path: src/test/java_inactive/DynamicDispatchDemo.java
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import org.dynalang.dynalink.MonomorphicCallSite;
import org.dynalang.dynalink.RelinkableCallSite;
import org.dynalang.dynalink.linker.CallSiteDescriptor;
public class DynamicDispatchDemo {
public static class English {
public void sayHello() {
System.out.println("Hello!");
}
}
public static class Spanish {
public void sayHello() {
System.out.println("Hola!");
}
}
public static void main(String[] args) throws Throwable {
final Object[] greeters =
new Object[] { new English(), new Spanish(), new English(),
new Spanish(), new Spanish(), new English(),
new English() };
final MethodHandle sayHelloInvoker =
new DynamicIndy().invokeDynamic("sayHello", MethodType
.methodType(Void.TYPE), DynamicDispatchDemo.class,
"bootstrap", MethodType.methodType(CallSite.class,
MethodHandles.Lookup.class, String.class,
MethodType.class));
for(Object greeter: greeters) {
sayHelloInvoker.invokeGeneric(greeter);
}
}
public static CallSite bootstrap(MethodHandles.Lookup lookup, String name,
MethodType callSiteType) { | final CallSite cs = new MonomorphicCallSite(lookup, name, callSiteType); |
szegedi/dynalink | src/test/java_inactive/DynamicDispatchDemo.java | // Path: src/main/java/org/dynalang/dynalink/MonomorphicCallSite.java
// public class MonomorphicCallSite extends AbstractRelinkableCallSite {
// /**
// * Creates a new call site with monomorphic inline caching strategy.
// * @param descriptor the descriptor for this call site
// */
// public MonomorphicCallSite(final CallSiteDescriptor descriptor) {
// super(descriptor);
// }
//
// @Override
// public void relink(final GuardedInvocation guardedInvocation, final MethodHandle relink) {
// setTarget(guardedInvocation.compose(relink));
// }
//
// @Override
// public void resetAndRelink(final GuardedInvocation guardedInvocation, final MethodHandle relink) {
// relink(guardedInvocation, relink);
// }
// }
//
// Path: src/main/java/org/dynalang/dynalink/RelinkableCallSite.java
// public interface RelinkableCallSite {
// /**
// * Initializes the relinkable call site by setting a relink-and-invoke method handle. The call site implementation
// * is supposed to set this method handle as its target.
// * @param relinkAndInvoke a relink-and-invoke method handle supplied by the {@link DynamicLinker}.
// */
// public void initialize(MethodHandle relinkAndInvoke);
//
// /**
// * Returns the descriptor for this call site.
// *
// * @return the descriptor for this call site.
// */
// public CallSiteDescriptor getDescriptor();
//
// /**
// * This method will be called by the dynamic linker every time the call site is normally relinked. It will be passed
// * a {@code GuardedInvocation} that the call site should incorporate into its target method handle. When this method
// * is called, the call site is allowed to keep other non-invalidated invocations around for implementation of
// * polymorphic inline caches and compose them with this invocation to form its final target.
// *
// * @param guardedInvocation the guarded invocation that the call site should incorporate into its target method
// * handle.
// * @param fallback the fallback method. This is a method matching the method type of the call site that is supplied
// * by the {@link DynamicLinker} to be used by this call site as a fallback when it can't invoke its target with the
// * passed arguments. The fallback method is such that when it's invoked, it'll try to discover the adequate target
// * for the invocation, subsequently invoke {@link #relink(GuardedInvocation, MethodHandle)} or
// * {@link #resetAndRelink(GuardedInvocation, MethodHandle)}, and finally invoke the target.
// */
// public void relink(GuardedInvocation guardedInvocation, MethodHandle fallback);
//
// /**
// * This method will be called by the dynamic linker every time the call site is relinked and the linker wishes the
// * call site to throw away any prior linkage state. It will be passed a {@code GuardedInvocation} that the call site
// * should use to build its target method handle. When this method is called, the call site is discouraged from
// * keeping previous state around, and is supposed to only link the current invocation.
// *
// * @param guardedInvocation the guarded invocation that the call site should use to build its target method handle.
// * @param fallback the fallback method. This is a method matching the method type of the call site that is supplied
// * by the {@link DynamicLinker} to be used by this call site as a fallback when it can't invoke its target with the
// * passed arguments. The fallback method is such that when it's invoked, it'll try to discover the adequate target
// * for the invocation, subsequently invoke {@link #relink(GuardedInvocation, MethodHandle)} or
// * {@link #resetAndRelink(GuardedInvocation, MethodHandle)}, and finally invoke the target.
// */
// public void resetAndRelink(GuardedInvocation guardedInvocation, MethodHandle fallback);
// }
| import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import org.dynalang.dynalink.MonomorphicCallSite;
import org.dynalang.dynalink.RelinkableCallSite;
import org.dynalang.dynalink.linker.CallSiteDescriptor; |
for(Object greeter: greeters) {
sayHelloInvoker.invokeGeneric(greeter);
}
}
public static CallSite bootstrap(MethodHandles.Lookup lookup, String name,
MethodType callSiteType) {
final CallSite cs = new MonomorphicCallSite(lookup, name, callSiteType);
MethodHandle boundInvoker =
MethodHandles.insertArguments(INVOKE_DYNAMICALLY, 0, cs);
MethodHandle collectedArgsInvoker =
boundInvoker.asCollector(Object.class, callSiteType
.parameterCount()
- boundInvoker.type().parameterCount() + 1);
MethodHandle convertedArgsInvoker =
MethodHandles.convertArguments(collectedArgsInvoker,
callSiteType);
cs.setTarget(convertedArgsInvoker);
return cs;
}
private static MethodHandle INVOKE_DYNAMICALLY;
static {
try {
INVOKE_DYNAMICALLY =
MethodHandles.lookup().findStatic(
DynamicDispatchDemo.class,
"invokeDynamically",
MethodType.methodType(Object.class, | // Path: src/main/java/org/dynalang/dynalink/MonomorphicCallSite.java
// public class MonomorphicCallSite extends AbstractRelinkableCallSite {
// /**
// * Creates a new call site with monomorphic inline caching strategy.
// * @param descriptor the descriptor for this call site
// */
// public MonomorphicCallSite(final CallSiteDescriptor descriptor) {
// super(descriptor);
// }
//
// @Override
// public void relink(final GuardedInvocation guardedInvocation, final MethodHandle relink) {
// setTarget(guardedInvocation.compose(relink));
// }
//
// @Override
// public void resetAndRelink(final GuardedInvocation guardedInvocation, final MethodHandle relink) {
// relink(guardedInvocation, relink);
// }
// }
//
// Path: src/main/java/org/dynalang/dynalink/RelinkableCallSite.java
// public interface RelinkableCallSite {
// /**
// * Initializes the relinkable call site by setting a relink-and-invoke method handle. The call site implementation
// * is supposed to set this method handle as its target.
// * @param relinkAndInvoke a relink-and-invoke method handle supplied by the {@link DynamicLinker}.
// */
// public void initialize(MethodHandle relinkAndInvoke);
//
// /**
// * Returns the descriptor for this call site.
// *
// * @return the descriptor for this call site.
// */
// public CallSiteDescriptor getDescriptor();
//
// /**
// * This method will be called by the dynamic linker every time the call site is normally relinked. It will be passed
// * a {@code GuardedInvocation} that the call site should incorporate into its target method handle. When this method
// * is called, the call site is allowed to keep other non-invalidated invocations around for implementation of
// * polymorphic inline caches and compose them with this invocation to form its final target.
// *
// * @param guardedInvocation the guarded invocation that the call site should incorporate into its target method
// * handle.
// * @param fallback the fallback method. This is a method matching the method type of the call site that is supplied
// * by the {@link DynamicLinker} to be used by this call site as a fallback when it can't invoke its target with the
// * passed arguments. The fallback method is such that when it's invoked, it'll try to discover the adequate target
// * for the invocation, subsequently invoke {@link #relink(GuardedInvocation, MethodHandle)} or
// * {@link #resetAndRelink(GuardedInvocation, MethodHandle)}, and finally invoke the target.
// */
// public void relink(GuardedInvocation guardedInvocation, MethodHandle fallback);
//
// /**
// * This method will be called by the dynamic linker every time the call site is relinked and the linker wishes the
// * call site to throw away any prior linkage state. It will be passed a {@code GuardedInvocation} that the call site
// * should use to build its target method handle. When this method is called, the call site is discouraged from
// * keeping previous state around, and is supposed to only link the current invocation.
// *
// * @param guardedInvocation the guarded invocation that the call site should use to build its target method handle.
// * @param fallback the fallback method. This is a method matching the method type of the call site that is supplied
// * by the {@link DynamicLinker} to be used by this call site as a fallback when it can't invoke its target with the
// * passed arguments. The fallback method is such that when it's invoked, it'll try to discover the adequate target
// * for the invocation, subsequently invoke {@link #relink(GuardedInvocation, MethodHandle)} or
// * {@link #resetAndRelink(GuardedInvocation, MethodHandle)}, and finally invoke the target.
// */
// public void resetAndRelink(GuardedInvocation guardedInvocation, MethodHandle fallback);
// }
// Path: src/test/java_inactive/DynamicDispatchDemo.java
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import org.dynalang.dynalink.MonomorphicCallSite;
import org.dynalang.dynalink.RelinkableCallSite;
import org.dynalang.dynalink.linker.CallSiteDescriptor;
for(Object greeter: greeters) {
sayHelloInvoker.invokeGeneric(greeter);
}
}
public static CallSite bootstrap(MethodHandles.Lookup lookup, String name,
MethodType callSiteType) {
final CallSite cs = new MonomorphicCallSite(lookup, name, callSiteType);
MethodHandle boundInvoker =
MethodHandles.insertArguments(INVOKE_DYNAMICALLY, 0, cs);
MethodHandle collectedArgsInvoker =
boundInvoker.asCollector(Object.class, callSiteType
.parameterCount()
- boundInvoker.type().parameterCount() + 1);
MethodHandle convertedArgsInvoker =
MethodHandles.convertArguments(collectedArgsInvoker,
callSiteType);
cs.setTarget(convertedArgsInvoker);
return cs;
}
private static MethodHandle INVOKE_DYNAMICALLY;
static {
try {
INVOKE_DYNAMICALLY =
MethodHandles.lookup().findStatic(
DynamicDispatchDemo.class,
"invokeDynamically",
MethodType.methodType(Object.class, | RelinkableCallSite.class, Object[].class)); |
szegedi/dynalink | src/main/java/org/dynalang/dynalink/support/NamedDynCallSiteDescriptor.java | // Path: src/main/java/org/dynalang/dynalink/CallSiteDescriptor.java
// public interface CallSiteDescriptor {
// /**
// * The index of the name token that will carry the operation scheme prefix (usually, "dyn").
// */
// public static final int SCHEME = 0;
// /**
// * The index of the name token that will usually carry the operation name.
// */
//
// public static final int OPERATOR=1;
// /**
// * The index of the name token that will usually carry a name of an operand (of a property, method, etc.)
// */
//
// public static final int NAME_OPERAND=2;
//
// /**
// * Character used to delimit tokens in an call site name.
// */
// public static final String TOKEN_DELIMITER = ":";
//
// /**
// * Character used to delimit operation names in a composite operation specification.
// */
// public static final String OPERATOR_DELIMITER = "|";
//
// /**
// * Returns the number of tokens in the name of the method at the call site. Method names are tokenized with the
// * colon ":" character, i.e. "dyn:getProp:color" would be the name used to describe a method that retrieves the
// * property named "color" on the object it is invoked on.
// * @return the number of tokens in the name of the method at the call site.
// */
// public int getNameTokenCount();
//
// /**
// * Returns the <i>i<sup>th</sup></i> token in the method name at the call site. Method names are tokenized with the
// * colon ":" character.
// * @param i the index of the token. Must be between 0 (inclusive) and {@link #getNameTokenCount()} (exclusive)
// * @throws IllegalArgumentException if the index is outside the allowed range.
// * @return the <i>i<sup>th</sup></i> token in the method name at the call site. The returned strings are interned.
// */
// public String getNameToken(int i);
//
// /**
// * Returns the name of the method at the call site. Note that the object internally only stores the tokenized name,
// * and has to reconstruct the full name from tokens on each invocation.
// * @return the name of the method at the call site.
// */
// public String getName();
//
// /**
// * The type of the method at the call site.
// *
// * @return type of the method at the call site.
// */
// public MethodType getMethodType();
//
// /**
// * Returns the lookup passed to the bootstrap method.
// * @return the lookup passed to the bootstrap method.
// */
// public Lookup getLookup();
//
// /**
// * Creates a new call site descriptor from this descriptor, which is identical to this, except it changes the method
// * type.
// *
// * @param newMethodType the new method type
// * @return a new call site descriptor, with the method type changed.
// */
// public CallSiteDescriptor changeMethodType(MethodType newMethodType);
//
// }
| import java.lang.invoke.MethodType;
import org.dynalang.dynalink.CallSiteDescriptor; | /*
Copyright 2009-2013 Attila Szegedi
Licensed under both the Apache License, Version 2.0 (the "Apache License")
and the BSD License (the "BSD License"), with licensee being free to
choose either of the two at their discretion.
You may not use this file except in compliance with either the Apache
License or the BSD License.
If you choose to use this file in compliance with the Apache License, the
following notice applies to you:
You may obtain a copy of the Apache 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.
If you choose to use this file in compliance with the BSD License, the
following notice applies to you:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.dynalang.dynalink.support;
class NamedDynCallSiteDescriptor extends UnnamedDynCallSiteDescriptor {
private final String name;
NamedDynCallSiteDescriptor(final String op, final String name, final MethodType methodType) {
super(op, methodType);
this.name = name;
}
@Override
public int getNameTokenCount() {
return 3;
}
@Override
public String getNameToken(final int i) {
switch(i) {
case 0: return "dyn";
case 1: return getOp();
case 2: return name;
default: throw new IndexOutOfBoundsException(String.valueOf(i));
}
}
@Override | // Path: src/main/java/org/dynalang/dynalink/CallSiteDescriptor.java
// public interface CallSiteDescriptor {
// /**
// * The index of the name token that will carry the operation scheme prefix (usually, "dyn").
// */
// public static final int SCHEME = 0;
// /**
// * The index of the name token that will usually carry the operation name.
// */
//
// public static final int OPERATOR=1;
// /**
// * The index of the name token that will usually carry a name of an operand (of a property, method, etc.)
// */
//
// public static final int NAME_OPERAND=2;
//
// /**
// * Character used to delimit tokens in an call site name.
// */
// public static final String TOKEN_DELIMITER = ":";
//
// /**
// * Character used to delimit operation names in a composite operation specification.
// */
// public static final String OPERATOR_DELIMITER = "|";
//
// /**
// * Returns the number of tokens in the name of the method at the call site. Method names are tokenized with the
// * colon ":" character, i.e. "dyn:getProp:color" would be the name used to describe a method that retrieves the
// * property named "color" on the object it is invoked on.
// * @return the number of tokens in the name of the method at the call site.
// */
// public int getNameTokenCount();
//
// /**
// * Returns the <i>i<sup>th</sup></i> token in the method name at the call site. Method names are tokenized with the
// * colon ":" character.
// * @param i the index of the token. Must be between 0 (inclusive) and {@link #getNameTokenCount()} (exclusive)
// * @throws IllegalArgumentException if the index is outside the allowed range.
// * @return the <i>i<sup>th</sup></i> token in the method name at the call site. The returned strings are interned.
// */
// public String getNameToken(int i);
//
// /**
// * Returns the name of the method at the call site. Note that the object internally only stores the tokenized name,
// * and has to reconstruct the full name from tokens on each invocation.
// * @return the name of the method at the call site.
// */
// public String getName();
//
// /**
// * The type of the method at the call site.
// *
// * @return type of the method at the call site.
// */
// public MethodType getMethodType();
//
// /**
// * Returns the lookup passed to the bootstrap method.
// * @return the lookup passed to the bootstrap method.
// */
// public Lookup getLookup();
//
// /**
// * Creates a new call site descriptor from this descriptor, which is identical to this, except it changes the method
// * type.
// *
// * @param newMethodType the new method type
// * @return a new call site descriptor, with the method type changed.
// */
// public CallSiteDescriptor changeMethodType(MethodType newMethodType);
//
// }
// Path: src/main/java/org/dynalang/dynalink/support/NamedDynCallSiteDescriptor.java
import java.lang.invoke.MethodType;
import org.dynalang.dynalink.CallSiteDescriptor;
/*
Copyright 2009-2013 Attila Szegedi
Licensed under both the Apache License, Version 2.0 (the "Apache License")
and the BSD License (the "BSD License"), with licensee being free to
choose either of the two at their discretion.
You may not use this file except in compliance with either the Apache
License or the BSD License.
If you choose to use this file in compliance with the Apache License, the
following notice applies to you:
You may obtain a copy of the Apache 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.
If you choose to use this file in compliance with the BSD License, the
following notice applies to you:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.dynalang.dynalink.support;
class NamedDynCallSiteDescriptor extends UnnamedDynCallSiteDescriptor {
private final String name;
NamedDynCallSiteDescriptor(final String op, final String name, final MethodType methodType) {
super(op, methodType);
this.name = name;
}
@Override
public int getNameTokenCount() {
return 3;
}
@Override
public String getNameToken(final int i) {
switch(i) {
case 0: return "dyn";
case 1: return getOp();
case 2: return name;
default: throw new IndexOutOfBoundsException(String.valueOf(i));
}
}
@Override | public CallSiteDescriptor changeMethodType(final MethodType newMethodType) { |
szegedi/dynalink | src/main/java/org/dynalang/dynalink/support/DefaultCallSiteDescriptor.java | // Path: src/main/java/org/dynalang/dynalink/CallSiteDescriptor.java
// public interface CallSiteDescriptor {
// /**
// * The index of the name token that will carry the operation scheme prefix (usually, "dyn").
// */
// public static final int SCHEME = 0;
// /**
// * The index of the name token that will usually carry the operation name.
// */
//
// public static final int OPERATOR=1;
// /**
// * The index of the name token that will usually carry a name of an operand (of a property, method, etc.)
// */
//
// public static final int NAME_OPERAND=2;
//
// /**
// * Character used to delimit tokens in an call site name.
// */
// public static final String TOKEN_DELIMITER = ":";
//
// /**
// * Character used to delimit operation names in a composite operation specification.
// */
// public static final String OPERATOR_DELIMITER = "|";
//
// /**
// * Returns the number of tokens in the name of the method at the call site. Method names are tokenized with the
// * colon ":" character, i.e. "dyn:getProp:color" would be the name used to describe a method that retrieves the
// * property named "color" on the object it is invoked on.
// * @return the number of tokens in the name of the method at the call site.
// */
// public int getNameTokenCount();
//
// /**
// * Returns the <i>i<sup>th</sup></i> token in the method name at the call site. Method names are tokenized with the
// * colon ":" character.
// * @param i the index of the token. Must be between 0 (inclusive) and {@link #getNameTokenCount()} (exclusive)
// * @throws IllegalArgumentException if the index is outside the allowed range.
// * @return the <i>i<sup>th</sup></i> token in the method name at the call site. The returned strings are interned.
// */
// public String getNameToken(int i);
//
// /**
// * Returns the name of the method at the call site. Note that the object internally only stores the tokenized name,
// * and has to reconstruct the full name from tokens on each invocation.
// * @return the name of the method at the call site.
// */
// public String getName();
//
// /**
// * The type of the method at the call site.
// *
// * @return type of the method at the call site.
// */
// public MethodType getMethodType();
//
// /**
// * Returns the lookup passed to the bootstrap method.
// * @return the lookup passed to the bootstrap method.
// */
// public Lookup getLookup();
//
// /**
// * Creates a new call site descriptor from this descriptor, which is identical to this, except it changes the method
// * type.
// *
// * @param newMethodType the new method type
// * @return a new call site descriptor, with the method type changed.
// */
// public CallSiteDescriptor changeMethodType(MethodType newMethodType);
//
// }
| import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import org.dynalang.dynalink.CallSiteDescriptor; | /*
Copyright 2009-2013 Attila Szegedi
Licensed under both the Apache License, Version 2.0 (the "Apache License")
and the BSD License (the "BSD License"), with licensee being free to
choose either of the two at their discretion.
You may not use this file except in compliance with either the Apache
License or the BSD License.
If you choose to use this file in compliance with the Apache License, the
following notice applies to you:
You may obtain a copy of the Apache 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.
If you choose to use this file in compliance with the BSD License, the
following notice applies to you:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.dynalang.dynalink.support;
/**
* A default, fairly light implementation of a call site descriptor used for describing non-standard operations. It does
* not store {@link Lookup} objects but always returns the public lookup from its {@link #getLookup()} method. If you
* need to support non-public lookup, you can use {@link LookupCallSiteDescriptor}.
* @author Attila Szegedi
*/
class DefaultCallSiteDescriptor extends AbstractCallSiteDescriptor {
private final String[] tokenizedName;
private final MethodType methodType;
DefaultCallSiteDescriptor(final String[] tokenizedName, final MethodType methodType) {
this.tokenizedName = tokenizedName;
this.methodType = methodType;
}
@Override
public int getNameTokenCount() {
return tokenizedName.length;
}
@Override
public String getNameToken(final int i) {
try {
return tokenizedName[i];
} catch(final ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
String[] getTokenizedName() {
return tokenizedName;
}
@Override
public MethodType getMethodType() {
return methodType;
}
@Override | // Path: src/main/java/org/dynalang/dynalink/CallSiteDescriptor.java
// public interface CallSiteDescriptor {
// /**
// * The index of the name token that will carry the operation scheme prefix (usually, "dyn").
// */
// public static final int SCHEME = 0;
// /**
// * The index of the name token that will usually carry the operation name.
// */
//
// public static final int OPERATOR=1;
// /**
// * The index of the name token that will usually carry a name of an operand (of a property, method, etc.)
// */
//
// public static final int NAME_OPERAND=2;
//
// /**
// * Character used to delimit tokens in an call site name.
// */
// public static final String TOKEN_DELIMITER = ":";
//
// /**
// * Character used to delimit operation names in a composite operation specification.
// */
// public static final String OPERATOR_DELIMITER = "|";
//
// /**
// * Returns the number of tokens in the name of the method at the call site. Method names are tokenized with the
// * colon ":" character, i.e. "dyn:getProp:color" would be the name used to describe a method that retrieves the
// * property named "color" on the object it is invoked on.
// * @return the number of tokens in the name of the method at the call site.
// */
// public int getNameTokenCount();
//
// /**
// * Returns the <i>i<sup>th</sup></i> token in the method name at the call site. Method names are tokenized with the
// * colon ":" character.
// * @param i the index of the token. Must be between 0 (inclusive) and {@link #getNameTokenCount()} (exclusive)
// * @throws IllegalArgumentException if the index is outside the allowed range.
// * @return the <i>i<sup>th</sup></i> token in the method name at the call site. The returned strings are interned.
// */
// public String getNameToken(int i);
//
// /**
// * Returns the name of the method at the call site. Note that the object internally only stores the tokenized name,
// * and has to reconstruct the full name from tokens on each invocation.
// * @return the name of the method at the call site.
// */
// public String getName();
//
// /**
// * The type of the method at the call site.
// *
// * @return type of the method at the call site.
// */
// public MethodType getMethodType();
//
// /**
// * Returns the lookup passed to the bootstrap method.
// * @return the lookup passed to the bootstrap method.
// */
// public Lookup getLookup();
//
// /**
// * Creates a new call site descriptor from this descriptor, which is identical to this, except it changes the method
// * type.
// *
// * @param newMethodType the new method type
// * @return a new call site descriptor, with the method type changed.
// */
// public CallSiteDescriptor changeMethodType(MethodType newMethodType);
//
// }
// Path: src/main/java/org/dynalang/dynalink/support/DefaultCallSiteDescriptor.java
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import org.dynalang.dynalink.CallSiteDescriptor;
/*
Copyright 2009-2013 Attila Szegedi
Licensed under both the Apache License, Version 2.0 (the "Apache License")
and the BSD License (the "BSD License"), with licensee being free to
choose either of the two at their discretion.
You may not use this file except in compliance with either the Apache
License or the BSD License.
If you choose to use this file in compliance with the Apache License, the
following notice applies to you:
You may obtain a copy of the Apache 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.
If you choose to use this file in compliance with the BSD License, the
following notice applies to you:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.dynalang.dynalink.support;
/**
* A default, fairly light implementation of a call site descriptor used for describing non-standard operations. It does
* not store {@link Lookup} objects but always returns the public lookup from its {@link #getLookup()} method. If you
* need to support non-public lookup, you can use {@link LookupCallSiteDescriptor}.
* @author Attila Szegedi
*/
class DefaultCallSiteDescriptor extends AbstractCallSiteDescriptor {
private final String[] tokenizedName;
private final MethodType methodType;
DefaultCallSiteDescriptor(final String[] tokenizedName, final MethodType methodType) {
this.tokenizedName = tokenizedName;
this.methodType = methodType;
}
@Override
public int getNameTokenCount() {
return tokenizedName.length;
}
@Override
public String getNameToken(final int i) {
try {
return tokenizedName[i];
} catch(final ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
String[] getTokenizedName() {
return tokenizedName;
}
@Override
public MethodType getMethodType() {
return methodType;
}
@Override | public CallSiteDescriptor changeMethodType(final MethodType newMethodType) { |
szegedi/dynalink | src/main/java/org/dynalang/dynalink/support/LookupCallSiteDescriptor.java | // Path: src/main/java/org/dynalang/dynalink/CallSiteDescriptor.java
// public interface CallSiteDescriptor {
// /**
// * The index of the name token that will carry the operation scheme prefix (usually, "dyn").
// */
// public static final int SCHEME = 0;
// /**
// * The index of the name token that will usually carry the operation name.
// */
//
// public static final int OPERATOR=1;
// /**
// * The index of the name token that will usually carry a name of an operand (of a property, method, etc.)
// */
//
// public static final int NAME_OPERAND=2;
//
// /**
// * Character used to delimit tokens in an call site name.
// */
// public static final String TOKEN_DELIMITER = ":";
//
// /**
// * Character used to delimit operation names in a composite operation specification.
// */
// public static final String OPERATOR_DELIMITER = "|";
//
// /**
// * Returns the number of tokens in the name of the method at the call site. Method names are tokenized with the
// * colon ":" character, i.e. "dyn:getProp:color" would be the name used to describe a method that retrieves the
// * property named "color" on the object it is invoked on.
// * @return the number of tokens in the name of the method at the call site.
// */
// public int getNameTokenCount();
//
// /**
// * Returns the <i>i<sup>th</sup></i> token in the method name at the call site. Method names are tokenized with the
// * colon ":" character.
// * @param i the index of the token. Must be between 0 (inclusive) and {@link #getNameTokenCount()} (exclusive)
// * @throws IllegalArgumentException if the index is outside the allowed range.
// * @return the <i>i<sup>th</sup></i> token in the method name at the call site. The returned strings are interned.
// */
// public String getNameToken(int i);
//
// /**
// * Returns the name of the method at the call site. Note that the object internally only stores the tokenized name,
// * and has to reconstruct the full name from tokens on each invocation.
// * @return the name of the method at the call site.
// */
// public String getName();
//
// /**
// * The type of the method at the call site.
// *
// * @return type of the method at the call site.
// */
// public MethodType getMethodType();
//
// /**
// * Returns the lookup passed to the bootstrap method.
// * @return the lookup passed to the bootstrap method.
// */
// public Lookup getLookup();
//
// /**
// * Creates a new call site descriptor from this descriptor, which is identical to this, except it changes the method
// * type.
// *
// * @param newMethodType the new method type
// * @return a new call site descriptor, with the method type changed.
// */
// public CallSiteDescriptor changeMethodType(MethodType newMethodType);
//
// }
| import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import org.dynalang.dynalink.CallSiteDescriptor; | /*
Copyright 2009-2013 Attila Szegedi
Licensed under both the Apache License, Version 2.0 (the "Apache License")
and the BSD License (the "BSD License"), with licensee being free to
choose either of the two at their discretion.
You may not use this file except in compliance with either the Apache
License or the BSD License.
If you choose to use this file in compliance with the Apache License, the
following notice applies to you:
You may obtain a copy of the Apache 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.
If you choose to use this file in compliance with the BSD License, the
following notice applies to you:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.dynalang.dynalink.support;
/**
* A call site descriptor that stores a specific {@link Lookup}. It does not, however, store static bootstrap arguments.
* @author Attila Szegedi
*/
class LookupCallSiteDescriptor extends DefaultCallSiteDescriptor {
private final Lookup lookup;
/**
* Create a new call site descriptor from explicit information.
* @param tokenizedName the name of the method
* @param methodType the method type
* @param lookup the lookup
*/
LookupCallSiteDescriptor(final String[] tokenizedName, final MethodType methodType, final Lookup lookup) {
super(tokenizedName, methodType);
this.lookup = lookup;
}
@Override
public Lookup getLookup() {
return lookup;
}
@Override | // Path: src/main/java/org/dynalang/dynalink/CallSiteDescriptor.java
// public interface CallSiteDescriptor {
// /**
// * The index of the name token that will carry the operation scheme prefix (usually, "dyn").
// */
// public static final int SCHEME = 0;
// /**
// * The index of the name token that will usually carry the operation name.
// */
//
// public static final int OPERATOR=1;
// /**
// * The index of the name token that will usually carry a name of an operand (of a property, method, etc.)
// */
//
// public static final int NAME_OPERAND=2;
//
// /**
// * Character used to delimit tokens in an call site name.
// */
// public static final String TOKEN_DELIMITER = ":";
//
// /**
// * Character used to delimit operation names in a composite operation specification.
// */
// public static final String OPERATOR_DELIMITER = "|";
//
// /**
// * Returns the number of tokens in the name of the method at the call site. Method names are tokenized with the
// * colon ":" character, i.e. "dyn:getProp:color" would be the name used to describe a method that retrieves the
// * property named "color" on the object it is invoked on.
// * @return the number of tokens in the name of the method at the call site.
// */
// public int getNameTokenCount();
//
// /**
// * Returns the <i>i<sup>th</sup></i> token in the method name at the call site. Method names are tokenized with the
// * colon ":" character.
// * @param i the index of the token. Must be between 0 (inclusive) and {@link #getNameTokenCount()} (exclusive)
// * @throws IllegalArgumentException if the index is outside the allowed range.
// * @return the <i>i<sup>th</sup></i> token in the method name at the call site. The returned strings are interned.
// */
// public String getNameToken(int i);
//
// /**
// * Returns the name of the method at the call site. Note that the object internally only stores the tokenized name,
// * and has to reconstruct the full name from tokens on each invocation.
// * @return the name of the method at the call site.
// */
// public String getName();
//
// /**
// * The type of the method at the call site.
// *
// * @return type of the method at the call site.
// */
// public MethodType getMethodType();
//
// /**
// * Returns the lookup passed to the bootstrap method.
// * @return the lookup passed to the bootstrap method.
// */
// public Lookup getLookup();
//
// /**
// * Creates a new call site descriptor from this descriptor, which is identical to this, except it changes the method
// * type.
// *
// * @param newMethodType the new method type
// * @return a new call site descriptor, with the method type changed.
// */
// public CallSiteDescriptor changeMethodType(MethodType newMethodType);
//
// }
// Path: src/main/java/org/dynalang/dynalink/support/LookupCallSiteDescriptor.java
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import org.dynalang.dynalink.CallSiteDescriptor;
/*
Copyright 2009-2013 Attila Szegedi
Licensed under both the Apache License, Version 2.0 (the "Apache License")
and the BSD License (the "BSD License"), with licensee being free to
choose either of the two at their discretion.
You may not use this file except in compliance with either the Apache
License or the BSD License.
If you choose to use this file in compliance with the Apache License, the
following notice applies to you:
You may obtain a copy of the Apache 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.
If you choose to use this file in compliance with the BSD License, the
following notice applies to you:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.dynalang.dynalink.support;
/**
* A call site descriptor that stores a specific {@link Lookup}. It does not, however, store static bootstrap arguments.
* @author Attila Szegedi
*/
class LookupCallSiteDescriptor extends DefaultCallSiteDescriptor {
private final Lookup lookup;
/**
* Create a new call site descriptor from explicit information.
* @param tokenizedName the name of the method
* @param methodType the method type
* @param lookup the lookup
*/
LookupCallSiteDescriptor(final String[] tokenizedName, final MethodType methodType, final Lookup lookup) {
super(tokenizedName, methodType);
this.lookup = lookup;
}
@Override
public Lookup getLookup() {
return lookup;
}
@Override | public CallSiteDescriptor changeMethodType(final MethodType newMethodType) { |
szegedi/dynalink | src/main/java/org/dynalang/dynalink/support/UnnamedDynCallSiteDescriptor.java | // Path: src/main/java/org/dynalang/dynalink/CallSiteDescriptor.java
// public interface CallSiteDescriptor {
// /**
// * The index of the name token that will carry the operation scheme prefix (usually, "dyn").
// */
// public static final int SCHEME = 0;
// /**
// * The index of the name token that will usually carry the operation name.
// */
//
// public static final int OPERATOR=1;
// /**
// * The index of the name token that will usually carry a name of an operand (of a property, method, etc.)
// */
//
// public static final int NAME_OPERAND=2;
//
// /**
// * Character used to delimit tokens in an call site name.
// */
// public static final String TOKEN_DELIMITER = ":";
//
// /**
// * Character used to delimit operation names in a composite operation specification.
// */
// public static final String OPERATOR_DELIMITER = "|";
//
// /**
// * Returns the number of tokens in the name of the method at the call site. Method names are tokenized with the
// * colon ":" character, i.e. "dyn:getProp:color" would be the name used to describe a method that retrieves the
// * property named "color" on the object it is invoked on.
// * @return the number of tokens in the name of the method at the call site.
// */
// public int getNameTokenCount();
//
// /**
// * Returns the <i>i<sup>th</sup></i> token in the method name at the call site. Method names are tokenized with the
// * colon ":" character.
// * @param i the index of the token. Must be between 0 (inclusive) and {@link #getNameTokenCount()} (exclusive)
// * @throws IllegalArgumentException if the index is outside the allowed range.
// * @return the <i>i<sup>th</sup></i> token in the method name at the call site. The returned strings are interned.
// */
// public String getNameToken(int i);
//
// /**
// * Returns the name of the method at the call site. Note that the object internally only stores the tokenized name,
// * and has to reconstruct the full name from tokens on each invocation.
// * @return the name of the method at the call site.
// */
// public String getName();
//
// /**
// * The type of the method at the call site.
// *
// * @return type of the method at the call site.
// */
// public MethodType getMethodType();
//
// /**
// * Returns the lookup passed to the bootstrap method.
// * @return the lookup passed to the bootstrap method.
// */
// public Lookup getLookup();
//
// /**
// * Creates a new call site descriptor from this descriptor, which is identical to this, except it changes the method
// * type.
// *
// * @param newMethodType the new method type
// * @return a new call site descriptor, with the method type changed.
// */
// public CallSiteDescriptor changeMethodType(MethodType newMethodType);
//
// }
| import java.lang.invoke.MethodType;
import org.dynalang.dynalink.CallSiteDescriptor; | /*
Copyright 2009-2013 Attila Szegedi
Licensed under both the Apache License, Version 2.0 (the "Apache License")
and the BSD License (the "BSD License"), with licensee being free to
choose either of the two at their discretion.
You may not use this file except in compliance with either the Apache
License or the BSD License.
If you choose to use this file in compliance with the Apache License, the
following notice applies to you:
You may obtain a copy of the Apache 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.
If you choose to use this file in compliance with the BSD License, the
following notice applies to you:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.dynalang.dynalink.support;
class UnnamedDynCallSiteDescriptor extends AbstractCallSiteDescriptor {
private final MethodType methodType;
private final String op;
UnnamedDynCallSiteDescriptor(final String op, final MethodType methodType) {
this.op = op;
this.methodType = methodType;
}
@Override
public int getNameTokenCount() {
return 2;
}
String getOp() {
return op;
}
@Override
public String getNameToken(final int i) {
switch(i) {
case 0: return "dyn";
case 1: return op;
default: throw new IndexOutOfBoundsException(String.valueOf(i));
}
}
@Override
public MethodType getMethodType() {
return methodType;
}
@Override | // Path: src/main/java/org/dynalang/dynalink/CallSiteDescriptor.java
// public interface CallSiteDescriptor {
// /**
// * The index of the name token that will carry the operation scheme prefix (usually, "dyn").
// */
// public static final int SCHEME = 0;
// /**
// * The index of the name token that will usually carry the operation name.
// */
//
// public static final int OPERATOR=1;
// /**
// * The index of the name token that will usually carry a name of an operand (of a property, method, etc.)
// */
//
// public static final int NAME_OPERAND=2;
//
// /**
// * Character used to delimit tokens in an call site name.
// */
// public static final String TOKEN_DELIMITER = ":";
//
// /**
// * Character used to delimit operation names in a composite operation specification.
// */
// public static final String OPERATOR_DELIMITER = "|";
//
// /**
// * Returns the number of tokens in the name of the method at the call site. Method names are tokenized with the
// * colon ":" character, i.e. "dyn:getProp:color" would be the name used to describe a method that retrieves the
// * property named "color" on the object it is invoked on.
// * @return the number of tokens in the name of the method at the call site.
// */
// public int getNameTokenCount();
//
// /**
// * Returns the <i>i<sup>th</sup></i> token in the method name at the call site. Method names are tokenized with the
// * colon ":" character.
// * @param i the index of the token. Must be between 0 (inclusive) and {@link #getNameTokenCount()} (exclusive)
// * @throws IllegalArgumentException if the index is outside the allowed range.
// * @return the <i>i<sup>th</sup></i> token in the method name at the call site. The returned strings are interned.
// */
// public String getNameToken(int i);
//
// /**
// * Returns the name of the method at the call site. Note that the object internally only stores the tokenized name,
// * and has to reconstruct the full name from tokens on each invocation.
// * @return the name of the method at the call site.
// */
// public String getName();
//
// /**
// * The type of the method at the call site.
// *
// * @return type of the method at the call site.
// */
// public MethodType getMethodType();
//
// /**
// * Returns the lookup passed to the bootstrap method.
// * @return the lookup passed to the bootstrap method.
// */
// public Lookup getLookup();
//
// /**
// * Creates a new call site descriptor from this descriptor, which is identical to this, except it changes the method
// * type.
// *
// * @param newMethodType the new method type
// * @return a new call site descriptor, with the method type changed.
// */
// public CallSiteDescriptor changeMethodType(MethodType newMethodType);
//
// }
// Path: src/main/java/org/dynalang/dynalink/support/UnnamedDynCallSiteDescriptor.java
import java.lang.invoke.MethodType;
import org.dynalang.dynalink.CallSiteDescriptor;
/*
Copyright 2009-2013 Attila Szegedi
Licensed under both the Apache License, Version 2.0 (the "Apache License")
and the BSD License (the "BSD License"), with licensee being free to
choose either of the two at their discretion.
You may not use this file except in compliance with either the Apache
License or the BSD License.
If you choose to use this file in compliance with the Apache License, the
following notice applies to you:
You may obtain a copy of the Apache 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.
If you choose to use this file in compliance with the BSD License, the
following notice applies to you:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.dynalang.dynalink.support;
class UnnamedDynCallSiteDescriptor extends AbstractCallSiteDescriptor {
private final MethodType methodType;
private final String op;
UnnamedDynCallSiteDescriptor(final String op, final MethodType methodType) {
this.op = op;
this.methodType = methodType;
}
@Override
public int getNameTokenCount() {
return 2;
}
String getOp() {
return op;
}
@Override
public String getNameToken(final int i) {
switch(i) {
case 0: return "dyn";
case 1: return op;
default: throw new IndexOutOfBoundsException(String.valueOf(i));
}
}
@Override
public MethodType getMethodType() {
return methodType;
}
@Override | public CallSiteDescriptor changeMethodType(final MethodType newMethodType) { |
apache/hcatalog | src/test/org/apache/hcatalog/rcfile/TestRCFileMapReduceInputFormat.java | // Path: src/java/org/apache/hcatalog/rcfile/RCFileMapReduceInputFormat.java
// public class RCFileMapReduceInputFormat<K extends LongWritable,V extends BytesRefArrayWritable>
// extends FileInputFormat<LongWritable, BytesRefArrayWritable>
// {
//
// @Override
// public RecordReader<LongWritable,BytesRefArrayWritable> createRecordReader(InputSplit split,
// TaskAttemptContext context) throws IOException, InterruptedException {
//
// context.setStatus(split.toString());
// return new RCFileMapReduceRecordReader<LongWritable,BytesRefArrayWritable>();
// }
//
// @Override
// public List<InputSplit> getSplits(JobContext job) throws IOException {
//
// job.getConfiguration().setLong("mapred.min.split.size", SequenceFile.SYNC_INTERVAL);
// return super.getSplits(job);
// }
// }
| import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.io.RCFile;
import org.apache.hadoop.hive.ql.io.RCFileOutputFormat;
import org.apache.hadoop.hive.serde.Constants;
import org.apache.hadoop.hive.serde2.columnar.BytesRefArrayWritable;
import org.apache.hadoop.hive.serde2.columnar.BytesRefWritable;
import org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hcatalog.rcfile.RCFileMapReduceInputFormat; | }
private void splitAfterSync() throws IOException ,InterruptedException{
writeThenReadByRecordReader(500, 1000, 2, 19950, null);
}
private void writeThenReadByRecordReader(int intervalRecordCount,
int writeCount, int splitNumber, long maxSplitSize, CompressionCodec codec)
throws IOException, InterruptedException {
Path testDir = new Path(System.getProperty("test.data.dir", ".")
+ "/mapred/testsmallfirstsplit");
Path testFile = new Path(testDir, "test_rcfile");
fs.delete(testFile, true);
Configuration cloneConf = new Configuration(conf);
RCFileOutputFormat.setColumnNumber(cloneConf, bytesArray.length);
cloneConf.setInt(RCFile.RECORD_INTERVAL_CONF_STR, intervalRecordCount);
RCFile.Writer writer = new RCFile.Writer(fs, cloneConf, testFile, null, codec);
BytesRefArrayWritable bytes = new BytesRefArrayWritable(bytesArray.length);
for (int i = 0; i < bytesArray.length; i++) {
BytesRefWritable cu = null;
cu = new BytesRefWritable(bytesArray[i], 0, bytesArray[i].length);
bytes.set(i, cu);
}
for (int i = 0; i < writeCount; i++) {
writer.append(bytes);
}
writer.close();
| // Path: src/java/org/apache/hcatalog/rcfile/RCFileMapReduceInputFormat.java
// public class RCFileMapReduceInputFormat<K extends LongWritable,V extends BytesRefArrayWritable>
// extends FileInputFormat<LongWritable, BytesRefArrayWritable>
// {
//
// @Override
// public RecordReader<LongWritable,BytesRefArrayWritable> createRecordReader(InputSplit split,
// TaskAttemptContext context) throws IOException, InterruptedException {
//
// context.setStatus(split.toString());
// return new RCFileMapReduceRecordReader<LongWritable,BytesRefArrayWritable>();
// }
//
// @Override
// public List<InputSplit> getSplits(JobContext job) throws IOException {
//
// job.getConfiguration().setLong("mapred.min.split.size", SequenceFile.SYNC_INTERVAL);
// return super.getSplits(job);
// }
// }
// Path: src/test/org/apache/hcatalog/rcfile/TestRCFileMapReduceInputFormat.java
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.io.RCFile;
import org.apache.hadoop.hive.ql.io.RCFileOutputFormat;
import org.apache.hadoop.hive.serde.Constants;
import org.apache.hadoop.hive.serde2.columnar.BytesRefArrayWritable;
import org.apache.hadoop.hive.serde2.columnar.BytesRefWritable;
import org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hcatalog.rcfile.RCFileMapReduceInputFormat;
}
private void splitAfterSync() throws IOException ,InterruptedException{
writeThenReadByRecordReader(500, 1000, 2, 19950, null);
}
private void writeThenReadByRecordReader(int intervalRecordCount,
int writeCount, int splitNumber, long maxSplitSize, CompressionCodec codec)
throws IOException, InterruptedException {
Path testDir = new Path(System.getProperty("test.data.dir", ".")
+ "/mapred/testsmallfirstsplit");
Path testFile = new Path(testDir, "test_rcfile");
fs.delete(testFile, true);
Configuration cloneConf = new Configuration(conf);
RCFileOutputFormat.setColumnNumber(cloneConf, bytesArray.length);
cloneConf.setInt(RCFile.RECORD_INTERVAL_CONF_STR, intervalRecordCount);
RCFile.Writer writer = new RCFile.Writer(fs, cloneConf, testFile, null, codec);
BytesRefArrayWritable bytes = new BytesRefArrayWritable(bytesArray.length);
for (int i = 0; i < bytesArray.length; i++) {
BytesRefWritable cu = null;
cu = new BytesRefWritable(bytesArray[i], 0, bytesArray[i].length);
bytes.set(i, cu);
}
for (int i = 0; i < writeCount; i++) {
writer.append(bytes);
}
writer.close();
| RCFileMapReduceInputFormat<LongWritable, BytesRefArrayWritable> inputFormat = new RCFileMapReduceInputFormat<LongWritable, BytesRefArrayWritable>(); |
apache/hcatalog | src/java/org/apache/hcatalog/data/schema/HCatFieldSchema.java | // Path: src/java/org/apache/hcatalog/common/HCatException.java
// public class HCatException extends IOException {
//
// private static final long serialVersionUID = 1L;
//
// /** The error type enum for this exception. */
// private final ErrorType errorType;
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// */
// public HCatException(ErrorType errorType) {
// this(errorType, null, null);
// }
//
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, Throwable cause) {
// this(errorType, null, cause);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// */
// public HCatException(ErrorType errorType, String extraMessage) {
// this(errorType, extraMessage, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, String extraMessage, Throwable cause) {
// super(buildErrorMessage(
// errorType,
// extraMessage,
// cause), cause);
// this.errorType = errorType;
// }
//
//
// //TODO : remove default error type constructors after all exceptions
// //are changed to use error types
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// */
// public HCatException(String message) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// * @param cause the cause
// */
// public HCatException(String message, Throwable cause) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, cause);
// }
//
//
// /**
// * Builds the error message string. The error type message is appended with the extra message. If appendCause
// * is true for the error type, then the message of the cause also is added to the message.
// * @param type the error type
// * @param extraMessage the extra message string
// * @param cause the cause for the exception
// * @return the exception message string
// */
// public static String buildErrorMessage(ErrorType type, String extraMessage, Throwable cause) {
//
// //Initial message is just the error type message
// StringBuffer message = new StringBuffer(HCatException.class.getName());
// message.append(" : " + type.getErrorCode());
// message.append(" : " + type.getErrorMessage());
//
// if( extraMessage != null ) {
// //Add the extra message value to buffer
// message.append(" : " + extraMessage);
// }
//
// if( type.appendCauseMessage() ) {
// if( cause != null && cause.getMessage() != null ) {
// //Add the cause message to buffer
// message.append(". Cause : " + cause.toString());
// }
// }
//
// return message.toString();
// }
//
//
// /**
// * Is this a retriable error.
// * @return is it retriable
// */
// public boolean isRetriable() {
// return errorType.isRetriable();
// }
//
// /**
// * Gets the error type.
// * @return the error type enum
// */
// public ErrorType getErrorType() {
// return errorType;
// }
//
// /**
// * Gets the error code.
// * @return the error code
// */
// public int getErrorCode() {
// return errorType.getErrorCode();
// }
//
// /* (non-Javadoc)
// * @see java.lang.Throwable#toString()
// */
// @Override
// public String toString() {
// return getMessage();
// }
//
// }
| import java.io.Serializable;
import org.apache.hcatalog.common.HCatException; | public Type getType(){
return type;
}
/**
* Returns category of the field
* @return category of the field
*/
public Category getCategory(){
return category;
}
/**
* Returns name of the field
* @return name of the field
*/
public String getName(){
return fieldName;
}
public String getComment(){
return comment;
}
/**
* Constructor constructing a primitive datatype HCatFieldSchema
* @param fieldName Name of the primitive field
* @param type Type of the primitive field
* @throws HCatException if call made on non-primitive types
*/ | // Path: src/java/org/apache/hcatalog/common/HCatException.java
// public class HCatException extends IOException {
//
// private static final long serialVersionUID = 1L;
//
// /** The error type enum for this exception. */
// private final ErrorType errorType;
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// */
// public HCatException(ErrorType errorType) {
// this(errorType, null, null);
// }
//
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, Throwable cause) {
// this(errorType, null, cause);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// */
// public HCatException(ErrorType errorType, String extraMessage) {
// this(errorType, extraMessage, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, String extraMessage, Throwable cause) {
// super(buildErrorMessage(
// errorType,
// extraMessage,
// cause), cause);
// this.errorType = errorType;
// }
//
//
// //TODO : remove default error type constructors after all exceptions
// //are changed to use error types
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// */
// public HCatException(String message) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// * @param cause the cause
// */
// public HCatException(String message, Throwable cause) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, cause);
// }
//
//
// /**
// * Builds the error message string. The error type message is appended with the extra message. If appendCause
// * is true for the error type, then the message of the cause also is added to the message.
// * @param type the error type
// * @param extraMessage the extra message string
// * @param cause the cause for the exception
// * @return the exception message string
// */
// public static String buildErrorMessage(ErrorType type, String extraMessage, Throwable cause) {
//
// //Initial message is just the error type message
// StringBuffer message = new StringBuffer(HCatException.class.getName());
// message.append(" : " + type.getErrorCode());
// message.append(" : " + type.getErrorMessage());
//
// if( extraMessage != null ) {
// //Add the extra message value to buffer
// message.append(" : " + extraMessage);
// }
//
// if( type.appendCauseMessage() ) {
// if( cause != null && cause.getMessage() != null ) {
// //Add the cause message to buffer
// message.append(". Cause : " + cause.toString());
// }
// }
//
// return message.toString();
// }
//
//
// /**
// * Is this a retriable error.
// * @return is it retriable
// */
// public boolean isRetriable() {
// return errorType.isRetriable();
// }
//
// /**
// * Gets the error type.
// * @return the error type enum
// */
// public ErrorType getErrorType() {
// return errorType;
// }
//
// /**
// * Gets the error code.
// * @return the error code
// */
// public int getErrorCode() {
// return errorType.getErrorCode();
// }
//
// /* (non-Javadoc)
// * @see java.lang.Throwable#toString()
// */
// @Override
// public String toString() {
// return getMessage();
// }
//
// }
// Path: src/java/org/apache/hcatalog/data/schema/HCatFieldSchema.java
import java.io.Serializable;
import org.apache.hcatalog.common.HCatException;
public Type getType(){
return type;
}
/**
* Returns category of the field
* @return category of the field
*/
public Category getCategory(){
return category;
}
/**
* Returns name of the field
* @return name of the field
*/
public String getName(){
return fieldName;
}
public String getComment(){
return comment;
}
/**
* Constructor constructing a primitive datatype HCatFieldSchema
* @param fieldName Name of the primitive field
* @param type Type of the primitive field
* @throws HCatException if call made on non-primitive types
*/ | public HCatFieldSchema(String fieldName, Type type, String comment) throws HCatException { |
apache/hcatalog | src/java/org/apache/hcatalog/cli/SemanticAnalysis/CreateDatabaseHook.java | // Path: src/java/org/apache/hcatalog/common/HCatConstants.java
// public final class HCatConstants {
//
// /** The key for the input storage driver class name */
// public static final String HCAT_ISD_CLASS = "hcat.isd";
//
// /** The key for the output storage driver class name */
// public static final String HCAT_OSD_CLASS = "hcat.osd";
//
// public static final String HIVE_RCFILE_IF_CLASS = "org.apache.hadoop.hive.ql.io.RCFileInputFormat";
// public static final String HIVE_RCFILE_OF_CLASS = "org.apache.hadoop.hive.ql.io.RCFileOutputFormat";
// public static final String HCAT_RCFILE_ISD_CLASS = "org.apache.hcatalog.rcfile.RCFileInputDriver";
// public static final String HCAT_RCFILE_OSD_CLASS = "org.apache.hcatalog.rcfile.RCFileOutputDriver";
//
// //The keys used to store info into the job Configuration
// public static final String HCAT_KEY_BASE = "mapreduce.lib.hcat";
//
// public static final String HCAT_KEY_OUTPUT_SCHEMA = HCAT_KEY_BASE + ".output.schema";
//
// public static final String HCAT_KEY_JOB_INFO = HCAT_KEY_BASE + ".job.info";
//
// private HCatConstants() { // restrict instantiation
// }
//
// public static final String HCAT_TABLE_SCHEMA = "hcat.table.schema";
//
// public static final String HCAT_METASTORE_URI = "hcat.metastore.uri";
//
// public static final String HCAT_PERMS = "hcat.perms";
//
// public static final String HCAT_GROUP = "hcat.group";
//
// public static final String HCAT_CREATE_TBL_NAME = "hcat.create.tbl.name";
//
// public static final String HCAT_CREATE_DB_NAME = "hcat.create.db.name";
//
// public static final String HCAT_METASTORE_PRINCIPAL = "hcat.metastore.principal";
//
// // IMPORTANT IMPORTANT IMPORTANT!!!!!
// //The keys used to store info into the job Configuration.
// //If any new keys are added, the HowlStorer needs to be updated. The HowlStorer
// //updates the job configuration in the backend to insert these keys to avoid
// //having to call setOutput from the backend (which would cause a metastore call
// //from the map jobs)
// public static final String HCAT_KEY_OUTPUT_BASE = "mapreduce.lib.hcatoutput";
// public static final String HCAT_KEY_OUTPUT_INFO = HCAT_KEY_OUTPUT_BASE + ".info";
// public static final String HCAT_KEY_HIVE_CONF = HCAT_KEY_OUTPUT_BASE + ".hive.conf";
// public static final String HCAT_KEY_TOKEN_SIGNATURE = HCAT_KEY_OUTPUT_BASE + ".token.sig";
// }
| import java.io.Serializable;
import java.util.List;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.AbstractSemanticAnalyzerHook;
import org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer;
import org.apache.hadoop.hive.ql.parse.HiveParser;
import org.apache.hadoop.hive.ql.parse.HiveSemanticAnalyzerHookContext;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hcatalog.common.HCatConstants; |
databaseName = BaseSemanticAnalyzer.getUnescapedName((ASTNode)ast.getChild(0));
for (int num = 1; num < numCh; num++) {
ASTNode child = (ASTNode) ast.getChild(num);
switch (child.getToken().getType()) {
case HiveParser.TOK_QUERY: // CTAS
throw new SemanticException("Operation not supported. Create db as Select is not a valid operation.");
case HiveParser.TOK_IFNOTEXISTS:
try {
List<String> dbs = db.getDatabasesByPattern(databaseName);
if (dbs != null && dbs.size() > 0) { // db exists
return ast;
}
} catch (HiveException e) {
throw new SemanticException(e);
}
break;
}
}
return ast;
}
@Override
public void postAnalyze(HiveSemanticAnalyzerHookContext context,
List<Task<? extends Serializable>> rootTasks) throws SemanticException { | // Path: src/java/org/apache/hcatalog/common/HCatConstants.java
// public final class HCatConstants {
//
// /** The key for the input storage driver class name */
// public static final String HCAT_ISD_CLASS = "hcat.isd";
//
// /** The key for the output storage driver class name */
// public static final String HCAT_OSD_CLASS = "hcat.osd";
//
// public static final String HIVE_RCFILE_IF_CLASS = "org.apache.hadoop.hive.ql.io.RCFileInputFormat";
// public static final String HIVE_RCFILE_OF_CLASS = "org.apache.hadoop.hive.ql.io.RCFileOutputFormat";
// public static final String HCAT_RCFILE_ISD_CLASS = "org.apache.hcatalog.rcfile.RCFileInputDriver";
// public static final String HCAT_RCFILE_OSD_CLASS = "org.apache.hcatalog.rcfile.RCFileOutputDriver";
//
// //The keys used to store info into the job Configuration
// public static final String HCAT_KEY_BASE = "mapreduce.lib.hcat";
//
// public static final String HCAT_KEY_OUTPUT_SCHEMA = HCAT_KEY_BASE + ".output.schema";
//
// public static final String HCAT_KEY_JOB_INFO = HCAT_KEY_BASE + ".job.info";
//
// private HCatConstants() { // restrict instantiation
// }
//
// public static final String HCAT_TABLE_SCHEMA = "hcat.table.schema";
//
// public static final String HCAT_METASTORE_URI = "hcat.metastore.uri";
//
// public static final String HCAT_PERMS = "hcat.perms";
//
// public static final String HCAT_GROUP = "hcat.group";
//
// public static final String HCAT_CREATE_TBL_NAME = "hcat.create.tbl.name";
//
// public static final String HCAT_CREATE_DB_NAME = "hcat.create.db.name";
//
// public static final String HCAT_METASTORE_PRINCIPAL = "hcat.metastore.principal";
//
// // IMPORTANT IMPORTANT IMPORTANT!!!!!
// //The keys used to store info into the job Configuration.
// //If any new keys are added, the HowlStorer needs to be updated. The HowlStorer
// //updates the job configuration in the backend to insert these keys to avoid
// //having to call setOutput from the backend (which would cause a metastore call
// //from the map jobs)
// public static final String HCAT_KEY_OUTPUT_BASE = "mapreduce.lib.hcatoutput";
// public static final String HCAT_KEY_OUTPUT_INFO = HCAT_KEY_OUTPUT_BASE + ".info";
// public static final String HCAT_KEY_HIVE_CONF = HCAT_KEY_OUTPUT_BASE + ".hive.conf";
// public static final String HCAT_KEY_TOKEN_SIGNATURE = HCAT_KEY_OUTPUT_BASE + ".token.sig";
// }
// Path: src/java/org/apache/hcatalog/cli/SemanticAnalysis/CreateDatabaseHook.java
import java.io.Serializable;
import java.util.List;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.AbstractSemanticAnalyzerHook;
import org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer;
import org.apache.hadoop.hive.ql.parse.HiveParser;
import org.apache.hadoop.hive.ql.parse.HiveSemanticAnalyzerHookContext;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hcatalog.common.HCatConstants;
databaseName = BaseSemanticAnalyzer.getUnescapedName((ASTNode)ast.getChild(0));
for (int num = 1; num < numCh; num++) {
ASTNode child = (ASTNode) ast.getChild(num);
switch (child.getToken().getType()) {
case HiveParser.TOK_QUERY: // CTAS
throw new SemanticException("Operation not supported. Create db as Select is not a valid operation.");
case HiveParser.TOK_IFNOTEXISTS:
try {
List<String> dbs = db.getDatabasesByPattern(databaseName);
if (dbs != null && dbs.size() > 0) { // db exists
return ast;
}
} catch (HiveException e) {
throw new SemanticException(e);
}
break;
}
}
return ast;
}
@Override
public void postAnalyze(HiveSemanticAnalyzerHookContext context,
List<Task<? extends Serializable>> rootTasks) throws SemanticException { | context.getConf().set(HCatConstants.HCAT_CREATE_DB_NAME, databaseName); |
apache/hcatalog | src/test/org/apache/hcatalog/pig/TestHCatLoader.java | // Path: src/java/org/apache/hcatalog/data/Pair.java
// public class Pair<T, U> implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public T first;
// public U second;
//
// /**
// * @param f First element in pair.
// * @param s Second element in pair.
// */
// public Pair(T f, U s) {
// first = f;
// second = s;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return "[" + first.toString() +"," + second.toString() + "]";
// }
//
// @Override
// public int hashCode() {
// return (((this.first == null ? 1 : this.first.hashCode()) * 17)
// + (this.second == null ? 1 : this.second.hashCode()) * 19);
// }
//
// @Override
// public boolean equals(Object other) {
// if(other == null) {
// return false;
// }
//
// if(! (other instanceof Pair)) {
// return false;
// }
//
// Pair otherPair = (Pair) other;
//
// if(this.first == null) {
// if(otherPair.first != null) {
// return false;
// } else {
// return true;
// }
// }
//
// if(this.second == null) {
// if(otherPair.second != null) {
// return false;
// } else {
// return true;
// }
// }
//
// if(this.first.equals(otherPair.first) && this.second.equals(otherPair.second)) {
// return true;
// } else {
// return false;
// }
// }
// }
| import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import junit.framework.TestCase;
import org.apache.hadoop.hive.cli.CliSessionState;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hcatalog.MiniCluster;
import org.apache.hcatalog.data.Pair;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema;
import org.apache.pig.impl.util.UDFContext; | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.pig;
public class TestHCatLoader extends TestCase {
private static final String BASIC_TABLE = "junit_unparted_basic";
private static final String COMPLEX_TABLE = "junit_unparted_complex";
private static final String PARTITIONED_TABLE = "junit_parted_basic";
private static MiniCluster cluster = MiniCluster.buildCluster();
private static Driver driver;
private static Properties props;
private static final String basicFile = "/tmp/basic.input.data";
private static final String complexFile = "/tmp/complex.input.data";
private static String fullFileNameBasic;
private static String fullFileNameComplex;
private static int guardTestCount = 5; // ugh, instantiate using introspection in guardedSetupBeforeClass
private static boolean setupHasRun = false;
| // Path: src/java/org/apache/hcatalog/data/Pair.java
// public class Pair<T, U> implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public T first;
// public U second;
//
// /**
// * @param f First element in pair.
// * @param s Second element in pair.
// */
// public Pair(T f, U s) {
// first = f;
// second = s;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return "[" + first.toString() +"," + second.toString() + "]";
// }
//
// @Override
// public int hashCode() {
// return (((this.first == null ? 1 : this.first.hashCode()) * 17)
// + (this.second == null ? 1 : this.second.hashCode()) * 19);
// }
//
// @Override
// public boolean equals(Object other) {
// if(other == null) {
// return false;
// }
//
// if(! (other instanceof Pair)) {
// return false;
// }
//
// Pair otherPair = (Pair) other;
//
// if(this.first == null) {
// if(otherPair.first != null) {
// return false;
// } else {
// return true;
// }
// }
//
// if(this.second == null) {
// if(otherPair.second != null) {
// return false;
// } else {
// return true;
// }
// }
//
// if(this.first.equals(otherPair.first) && this.second.equals(otherPair.second)) {
// return true;
// } else {
// return false;
// }
// }
// }
// Path: src/test/org/apache/hcatalog/pig/TestHCatLoader.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import junit.framework.TestCase;
import org.apache.hadoop.hive.cli.CliSessionState;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hcatalog.MiniCluster;
import org.apache.hcatalog.data.Pair;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema;
import org.apache.pig.impl.util.UDFContext;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.pig;
public class TestHCatLoader extends TestCase {
private static final String BASIC_TABLE = "junit_unparted_basic";
private static final String COMPLEX_TABLE = "junit_unparted_complex";
private static final String PARTITIONED_TABLE = "junit_parted_basic";
private static MiniCluster cluster = MiniCluster.buildCluster();
private static Driver driver;
private static Properties props;
private static final String basicFile = "/tmp/basic.input.data";
private static final String complexFile = "/tmp/complex.input.data";
private static String fullFileNameBasic;
private static String fullFileNameComplex;
private static int guardTestCount = 5; // ugh, instantiate using introspection in guardedSetupBeforeClass
private static boolean setupHasRun = false;
| private static Map<Integer,Pair<Integer,String>> basicInputData; |
apache/hcatalog | src/test/org/apache/hcatalog/pig/TestHCatStorerMulti.java | // Path: src/java/org/apache/hcatalog/data/Pair.java
// public class Pair<T, U> implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public T first;
// public U second;
//
// /**
// * @param f First element in pair.
// * @param s Second element in pair.
// */
// public Pair(T f, U s) {
// first = f;
// second = s;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return "[" + first.toString() +"," + second.toString() + "]";
// }
//
// @Override
// public int hashCode() {
// return (((this.first == null ? 1 : this.first.hashCode()) * 17)
// + (this.second == null ? 1 : this.second.hashCode()) * 19);
// }
//
// @Override
// public boolean equals(Object other) {
// if(other == null) {
// return false;
// }
//
// if(! (other instanceof Pair)) {
// return false;
// }
//
// Pair otherPair = (Pair) other;
//
// if(this.first == null) {
// if(otherPair.first != null) {
// return false;
// } else {
// return true;
// }
// }
//
// if(this.second == null) {
// if(otherPair.second != null) {
// return false;
// } else {
// return true;
// }
// }
//
// if(this.first.equals(otherPair.first) && this.second.equals(otherPair.second)) {
// return true;
// } else {
// return false;
// }
// }
// }
| import org.apache.hcatalog.data.Pair;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.impl.util.UDFContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import junit.framework.TestCase;
import org.apache.hadoop.hive.cli.CliSessionState;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hcatalog.MiniCluster; | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.pig;
public class TestHCatStorerMulti extends TestCase {
private static final String BASIC_TABLE = "junit_unparted_basic";
private static final String PARTITIONED_TABLE = "junit_parted_basic";
private static MiniCluster cluster = MiniCluster.buildCluster();
private static Driver driver;
private static final String basicFile = "/tmp/basic.input.data";
private static String basicFileFullName;
private static Properties props;
| // Path: src/java/org/apache/hcatalog/data/Pair.java
// public class Pair<T, U> implements Serializable {
//
// private static final long serialVersionUID = 1L;
// public T first;
// public U second;
//
// /**
// * @param f First element in pair.
// * @param s Second element in pair.
// */
// public Pair(T f, U s) {
// first = f;
// second = s;
// }
//
// /* (non-Javadoc)
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return "[" + first.toString() +"," + second.toString() + "]";
// }
//
// @Override
// public int hashCode() {
// return (((this.first == null ? 1 : this.first.hashCode()) * 17)
// + (this.second == null ? 1 : this.second.hashCode()) * 19);
// }
//
// @Override
// public boolean equals(Object other) {
// if(other == null) {
// return false;
// }
//
// if(! (other instanceof Pair)) {
// return false;
// }
//
// Pair otherPair = (Pair) other;
//
// if(this.first == null) {
// if(otherPair.first != null) {
// return false;
// } else {
// return true;
// }
// }
//
// if(this.second == null) {
// if(otherPair.second != null) {
// return false;
// } else {
// return true;
// }
// }
//
// if(this.first.equals(otherPair.first) && this.second.equals(otherPair.second)) {
// return true;
// } else {
// return false;
// }
// }
// }
// Path: src/test/org/apache/hcatalog/pig/TestHCatStorerMulti.java
import org.apache.hcatalog.data.Pair;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.impl.util.UDFContext;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import junit.framework.TestCase;
import org.apache.hadoop.hive.cli.CliSessionState;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hcatalog.MiniCluster;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.pig;
public class TestHCatStorerMulti extends TestCase {
private static final String BASIC_TABLE = "junit_unparted_basic";
private static final String PARTITIONED_TABLE = "junit_parted_basic";
private static MiniCluster cluster = MiniCluster.buildCluster();
private static Driver driver;
private static final String basicFile = "/tmp/basic.input.data";
private static String basicFileFullName;
private static Properties props;
| private static Map<Integer,Pair<Integer,String>> basicInputData; |
apache/hcatalog | src/java/org/apache/hcatalog/mapreduce/HCatRecordWriter.java | // Path: src/java/org/apache/hcatalog/common/HCatException.java
// public class HCatException extends IOException {
//
// private static final long serialVersionUID = 1L;
//
// /** The error type enum for this exception. */
// private final ErrorType errorType;
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// */
// public HCatException(ErrorType errorType) {
// this(errorType, null, null);
// }
//
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, Throwable cause) {
// this(errorType, null, cause);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// */
// public HCatException(ErrorType errorType, String extraMessage) {
// this(errorType, extraMessage, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, String extraMessage, Throwable cause) {
// super(buildErrorMessage(
// errorType,
// extraMessage,
// cause), cause);
// this.errorType = errorType;
// }
//
//
// //TODO : remove default error type constructors after all exceptions
// //are changed to use error types
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// */
// public HCatException(String message) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// * @param cause the cause
// */
// public HCatException(String message, Throwable cause) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, cause);
// }
//
//
// /**
// * Builds the error message string. The error type message is appended with the extra message. If appendCause
// * is true for the error type, then the message of the cause also is added to the message.
// * @param type the error type
// * @param extraMessage the extra message string
// * @param cause the cause for the exception
// * @return the exception message string
// */
// public static String buildErrorMessage(ErrorType type, String extraMessage, Throwable cause) {
//
// //Initial message is just the error type message
// StringBuffer message = new StringBuffer(HCatException.class.getName());
// message.append(" : " + type.getErrorCode());
// message.append(" : " + type.getErrorMessage());
//
// if( extraMessage != null ) {
// //Add the extra message value to buffer
// message.append(" : " + extraMessage);
// }
//
// if( type.appendCauseMessage() ) {
// if( cause != null && cause.getMessage() != null ) {
// //Add the cause message to buffer
// message.append(". Cause : " + cause.toString());
// }
// }
//
// return message.toString();
// }
//
//
// /**
// * Is this a retriable error.
// * @return is it retriable
// */
// public boolean isRetriable() {
// return errorType.isRetriable();
// }
//
// /**
// * Gets the error type.
// * @return the error type enum
// */
// public ErrorType getErrorType() {
// return errorType;
// }
//
// /**
// * Gets the error code.
// * @return the error code
// */
// public int getErrorCode() {
// return errorType.getErrorCode();
// }
//
// /* (non-Javadoc)
// * @see java.lang.Throwable#toString()
// */
// @Override
// public String toString() {
// return getMessage();
// }
//
// }
| import java.io.IOException;
import java.util.List;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hcatalog.common.HCatException;
import org.apache.hcatalog.data.HCatRecord; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.mapreduce;
public class HCatRecordWriter extends RecordWriter<WritableComparable<?>, HCatRecord> {
private final HCatOutputStorageDriver storageDriver;
/**
* @return the storageDriver
*/
public HCatOutputStorageDriver getStorageDriver() {
return storageDriver;
}
private final RecordWriter<? super WritableComparable<?>, ? super Writable> baseWriter;
private final List<Integer> partColsToDel;
public HCatRecordWriter(TaskAttemptContext context) throws IOException, InterruptedException {
OutputJobInfo jobInfo = HCatOutputFormat.getJobInfo(context);
// If partition columns occur in data, we want to remove them.
partColsToDel = jobInfo.getPosOfPartCols();
if(partColsToDel == null){ | // Path: src/java/org/apache/hcatalog/common/HCatException.java
// public class HCatException extends IOException {
//
// private static final long serialVersionUID = 1L;
//
// /** The error type enum for this exception. */
// private final ErrorType errorType;
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// */
// public HCatException(ErrorType errorType) {
// this(errorType, null, null);
// }
//
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, Throwable cause) {
// this(errorType, null, cause);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// */
// public HCatException(ErrorType errorType, String extraMessage) {
// this(errorType, extraMessage, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, String extraMessage, Throwable cause) {
// super(buildErrorMessage(
// errorType,
// extraMessage,
// cause), cause);
// this.errorType = errorType;
// }
//
//
// //TODO : remove default error type constructors after all exceptions
// //are changed to use error types
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// */
// public HCatException(String message) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// * @param cause the cause
// */
// public HCatException(String message, Throwable cause) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, cause);
// }
//
//
// /**
// * Builds the error message string. The error type message is appended with the extra message. If appendCause
// * is true for the error type, then the message of the cause also is added to the message.
// * @param type the error type
// * @param extraMessage the extra message string
// * @param cause the cause for the exception
// * @return the exception message string
// */
// public static String buildErrorMessage(ErrorType type, String extraMessage, Throwable cause) {
//
// //Initial message is just the error type message
// StringBuffer message = new StringBuffer(HCatException.class.getName());
// message.append(" : " + type.getErrorCode());
// message.append(" : " + type.getErrorMessage());
//
// if( extraMessage != null ) {
// //Add the extra message value to buffer
// message.append(" : " + extraMessage);
// }
//
// if( type.appendCauseMessage() ) {
// if( cause != null && cause.getMessage() != null ) {
// //Add the cause message to buffer
// message.append(". Cause : " + cause.toString());
// }
// }
//
// return message.toString();
// }
//
//
// /**
// * Is this a retriable error.
// * @return is it retriable
// */
// public boolean isRetriable() {
// return errorType.isRetriable();
// }
//
// /**
// * Gets the error type.
// * @return the error type enum
// */
// public ErrorType getErrorType() {
// return errorType;
// }
//
// /**
// * Gets the error code.
// * @return the error code
// */
// public int getErrorCode() {
// return errorType.getErrorCode();
// }
//
// /* (non-Javadoc)
// * @see java.lang.Throwable#toString()
// */
// @Override
// public String toString() {
// return getMessage();
// }
//
// }
// Path: src/java/org/apache/hcatalog/mapreduce/HCatRecordWriter.java
import java.io.IOException;
import java.util.List;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hcatalog.common.HCatException;
import org.apache.hcatalog.data.HCatRecord;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.mapreduce;
public class HCatRecordWriter extends RecordWriter<WritableComparable<?>, HCatRecord> {
private final HCatOutputStorageDriver storageDriver;
/**
* @return the storageDriver
*/
public HCatOutputStorageDriver getStorageDriver() {
return storageDriver;
}
private final RecordWriter<? super WritableComparable<?>, ? super Writable> baseWriter;
private final List<Integer> partColsToDel;
public HCatRecordWriter(TaskAttemptContext context) throws IOException, InterruptedException {
OutputJobInfo jobInfo = HCatOutputFormat.getJobInfo(context);
// If partition columns occur in data, we want to remove them.
partColsToDel = jobInfo.getPosOfPartCols();
if(partColsToDel == null){ | throw new HCatException("It seems that setSchema() is not called on " + |
apache/hcatalog | src/java/org/apache/hcatalog/data/DefaultHCatRecord.java | // Path: src/java/org/apache/hcatalog/common/HCatException.java
// public class HCatException extends IOException {
//
// private static final long serialVersionUID = 1L;
//
// /** The error type enum for this exception. */
// private final ErrorType errorType;
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// */
// public HCatException(ErrorType errorType) {
// this(errorType, null, null);
// }
//
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, Throwable cause) {
// this(errorType, null, cause);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// */
// public HCatException(ErrorType errorType, String extraMessage) {
// this(errorType, extraMessage, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, String extraMessage, Throwable cause) {
// super(buildErrorMessage(
// errorType,
// extraMessage,
// cause), cause);
// this.errorType = errorType;
// }
//
//
// //TODO : remove default error type constructors after all exceptions
// //are changed to use error types
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// */
// public HCatException(String message) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// * @param cause the cause
// */
// public HCatException(String message, Throwable cause) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, cause);
// }
//
//
// /**
// * Builds the error message string. The error type message is appended with the extra message. If appendCause
// * is true for the error type, then the message of the cause also is added to the message.
// * @param type the error type
// * @param extraMessage the extra message string
// * @param cause the cause for the exception
// * @return the exception message string
// */
// public static String buildErrorMessage(ErrorType type, String extraMessage, Throwable cause) {
//
// //Initial message is just the error type message
// StringBuffer message = new StringBuffer(HCatException.class.getName());
// message.append(" : " + type.getErrorCode());
// message.append(" : " + type.getErrorMessage());
//
// if( extraMessage != null ) {
// //Add the extra message value to buffer
// message.append(" : " + extraMessage);
// }
//
// if( type.appendCauseMessage() ) {
// if( cause != null && cause.getMessage() != null ) {
// //Add the cause message to buffer
// message.append(". Cause : " + cause.toString());
// }
// }
//
// return message.toString();
// }
//
//
// /**
// * Is this a retriable error.
// * @return is it retriable
// */
// public boolean isRetriable() {
// return errorType.isRetriable();
// }
//
// /**
// * Gets the error type.
// * @return the error type enum
// */
// public ErrorType getErrorType() {
// return errorType;
// }
//
// /**
// * Gets the error code.
// * @return the error code
// */
// public int getErrorCode() {
// return errorType.getErrorCode();
// }
//
// /* (non-Javadoc)
// * @see java.lang.Throwable#toString()
// */
// @Override
// public String toString() {
// return getMessage();
// }
//
// }
| import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hcatalog.common.HCatException;
import org.apache.hcatalog.data.schema.HCatSchema; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.data;
public class DefaultHCatRecord extends HCatRecord {
private final List<Object> contents;
public DefaultHCatRecord(){
contents = new ArrayList<Object>();
}
public DefaultHCatRecord(int size){
contents = new ArrayList<Object>(size);
for(int i=0; i < size; i++){
contents.add(null);
}
}
@Override | // Path: src/java/org/apache/hcatalog/common/HCatException.java
// public class HCatException extends IOException {
//
// private static final long serialVersionUID = 1L;
//
// /** The error type enum for this exception. */
// private final ErrorType errorType;
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// */
// public HCatException(ErrorType errorType) {
// this(errorType, null, null);
// }
//
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, Throwable cause) {
// this(errorType, null, cause);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// */
// public HCatException(ErrorType errorType, String extraMessage) {
// this(errorType, extraMessage, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, String extraMessage, Throwable cause) {
// super(buildErrorMessage(
// errorType,
// extraMessage,
// cause), cause);
// this.errorType = errorType;
// }
//
//
// //TODO : remove default error type constructors after all exceptions
// //are changed to use error types
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// */
// public HCatException(String message) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// * @param cause the cause
// */
// public HCatException(String message, Throwable cause) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, cause);
// }
//
//
// /**
// * Builds the error message string. The error type message is appended with the extra message. If appendCause
// * is true for the error type, then the message of the cause also is added to the message.
// * @param type the error type
// * @param extraMessage the extra message string
// * @param cause the cause for the exception
// * @return the exception message string
// */
// public static String buildErrorMessage(ErrorType type, String extraMessage, Throwable cause) {
//
// //Initial message is just the error type message
// StringBuffer message = new StringBuffer(HCatException.class.getName());
// message.append(" : " + type.getErrorCode());
// message.append(" : " + type.getErrorMessage());
//
// if( extraMessage != null ) {
// //Add the extra message value to buffer
// message.append(" : " + extraMessage);
// }
//
// if( type.appendCauseMessage() ) {
// if( cause != null && cause.getMessage() != null ) {
// //Add the cause message to buffer
// message.append(". Cause : " + cause.toString());
// }
// }
//
// return message.toString();
// }
//
//
// /**
// * Is this a retriable error.
// * @return is it retriable
// */
// public boolean isRetriable() {
// return errorType.isRetriable();
// }
//
// /**
// * Gets the error type.
// * @return the error type enum
// */
// public ErrorType getErrorType() {
// return errorType;
// }
//
// /**
// * Gets the error code.
// * @return the error code
// */
// public int getErrorCode() {
// return errorType.getErrorCode();
// }
//
// /* (non-Javadoc)
// * @see java.lang.Throwable#toString()
// */
// @Override
// public String toString() {
// return getMessage();
// }
//
// }
// Path: src/java/org/apache/hcatalog/data/DefaultHCatRecord.java
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hcatalog.common.HCatException;
import org.apache.hcatalog.data.schema.HCatSchema;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.data;
public class DefaultHCatRecord extends HCatRecord {
private final List<Object> contents;
public DefaultHCatRecord(){
contents = new ArrayList<Object>();
}
public DefaultHCatRecord(int size){
contents = new ArrayList<Object>(size);
for(int i=0; i < size; i++){
contents.add(null);
}
}
@Override | public void remove(int idx) throws HCatException { |
apache/hcatalog | src/java/org/apache/hcatalog/cli/HCatDriver.java | // Path: src/java/org/apache/hcatalog/common/HCatConstants.java
// public final class HCatConstants {
//
// /** The key for the input storage driver class name */
// public static final String HCAT_ISD_CLASS = "hcat.isd";
//
// /** The key for the output storage driver class name */
// public static final String HCAT_OSD_CLASS = "hcat.osd";
//
// public static final String HIVE_RCFILE_IF_CLASS = "org.apache.hadoop.hive.ql.io.RCFileInputFormat";
// public static final String HIVE_RCFILE_OF_CLASS = "org.apache.hadoop.hive.ql.io.RCFileOutputFormat";
// public static final String HCAT_RCFILE_ISD_CLASS = "org.apache.hcatalog.rcfile.RCFileInputDriver";
// public static final String HCAT_RCFILE_OSD_CLASS = "org.apache.hcatalog.rcfile.RCFileOutputDriver";
//
// //The keys used to store info into the job Configuration
// public static final String HCAT_KEY_BASE = "mapreduce.lib.hcat";
//
// public static final String HCAT_KEY_OUTPUT_SCHEMA = HCAT_KEY_BASE + ".output.schema";
//
// public static final String HCAT_KEY_JOB_INFO = HCAT_KEY_BASE + ".job.info";
//
// private HCatConstants() { // restrict instantiation
// }
//
// public static final String HCAT_TABLE_SCHEMA = "hcat.table.schema";
//
// public static final String HCAT_METASTORE_URI = "hcat.metastore.uri";
//
// public static final String HCAT_PERMS = "hcat.perms";
//
// public static final String HCAT_GROUP = "hcat.group";
//
// public static final String HCAT_CREATE_TBL_NAME = "hcat.create.tbl.name";
//
// public static final String HCAT_CREATE_DB_NAME = "hcat.create.db.name";
//
// public static final String HCAT_METASTORE_PRINCIPAL = "hcat.metastore.principal";
//
// // IMPORTANT IMPORTANT IMPORTANT!!!!!
// //The keys used to store info into the job Configuration.
// //If any new keys are added, the HowlStorer needs to be updated. The HowlStorer
// //updates the job configuration in the backend to insert these keys to avoid
// //having to call setOutput from the backend (which would cause a metastore call
// //from the map jobs)
// public static final String HCAT_KEY_OUTPUT_BASE = "mapreduce.lib.hcatoutput";
// public static final String HCAT_KEY_OUTPUT_INFO = HCAT_KEY_OUTPUT_BASE + ".info";
// public static final String HCAT_KEY_HIVE_CONF = HCAT_KEY_OUTPUT_BASE + ".hive.conf";
// public static final String HCAT_KEY_TOKEN_SIGNATURE = HCAT_KEY_OUTPUT_BASE + ".token.sig";
// }
| import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hcatalog.common.HCatConstants; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.cli;
public class HCatDriver extends Driver {
@Override
public CommandProcessorResponse run(String command) {
int ret = super.run(command).getResponseCode();
SessionState ss = SessionState.get();
if (ret == 0){
// Only attempt to do this, if cmd was successful.
ret = setFSPermsNGrp(ss);
}
// reset conf vars | // Path: src/java/org/apache/hcatalog/common/HCatConstants.java
// public final class HCatConstants {
//
// /** The key for the input storage driver class name */
// public static final String HCAT_ISD_CLASS = "hcat.isd";
//
// /** The key for the output storage driver class name */
// public static final String HCAT_OSD_CLASS = "hcat.osd";
//
// public static final String HIVE_RCFILE_IF_CLASS = "org.apache.hadoop.hive.ql.io.RCFileInputFormat";
// public static final String HIVE_RCFILE_OF_CLASS = "org.apache.hadoop.hive.ql.io.RCFileOutputFormat";
// public static final String HCAT_RCFILE_ISD_CLASS = "org.apache.hcatalog.rcfile.RCFileInputDriver";
// public static final String HCAT_RCFILE_OSD_CLASS = "org.apache.hcatalog.rcfile.RCFileOutputDriver";
//
// //The keys used to store info into the job Configuration
// public static final String HCAT_KEY_BASE = "mapreduce.lib.hcat";
//
// public static final String HCAT_KEY_OUTPUT_SCHEMA = HCAT_KEY_BASE + ".output.schema";
//
// public static final String HCAT_KEY_JOB_INFO = HCAT_KEY_BASE + ".job.info";
//
// private HCatConstants() { // restrict instantiation
// }
//
// public static final String HCAT_TABLE_SCHEMA = "hcat.table.schema";
//
// public static final String HCAT_METASTORE_URI = "hcat.metastore.uri";
//
// public static final String HCAT_PERMS = "hcat.perms";
//
// public static final String HCAT_GROUP = "hcat.group";
//
// public static final String HCAT_CREATE_TBL_NAME = "hcat.create.tbl.name";
//
// public static final String HCAT_CREATE_DB_NAME = "hcat.create.db.name";
//
// public static final String HCAT_METASTORE_PRINCIPAL = "hcat.metastore.principal";
//
// // IMPORTANT IMPORTANT IMPORTANT!!!!!
// //The keys used to store info into the job Configuration.
// //If any new keys are added, the HowlStorer needs to be updated. The HowlStorer
// //updates the job configuration in the backend to insert these keys to avoid
// //having to call setOutput from the backend (which would cause a metastore call
// //from the map jobs)
// public static final String HCAT_KEY_OUTPUT_BASE = "mapreduce.lib.hcatoutput";
// public static final String HCAT_KEY_OUTPUT_INFO = HCAT_KEY_OUTPUT_BASE + ".info";
// public static final String HCAT_KEY_HIVE_CONF = HCAT_KEY_OUTPUT_BASE + ".hive.conf";
// public static final String HCAT_KEY_TOKEN_SIGNATURE = HCAT_KEY_OUTPUT_BASE + ".token.sig";
// }
// Path: src/java/org/apache/hcatalog/cli/HCatDriver.java
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.ql.Driver;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hcatalog.common.HCatConstants;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.cli;
public class HCatDriver extends Driver {
@Override
public CommandProcessorResponse run(String command) {
int ret = super.run(command).getResponseCode();
SessionState ss = SessionState.get();
if (ret == 0){
// Only attempt to do this, if cmd was successful.
ret = setFSPermsNGrp(ss);
}
// reset conf vars | ss.getConf().set(HCatConstants.HCAT_CREATE_DB_NAME, ""); |
apache/hcatalog | src/test/org/apache/hcatalog/data/TestDefaultHCatRecord.java | // Path: src/java/org/apache/hcatalog/data/DefaultHCatRecord.java
// public class DefaultHCatRecord extends HCatRecord {
//
// private final List<Object> contents;
//
// public DefaultHCatRecord(){
// contents = new ArrayList<Object>();
// }
//
// public DefaultHCatRecord(int size){
// contents = new ArrayList<Object>(size);
// for(int i=0; i < size; i++){
// contents.add(null);
// }
// }
//
// @Override
// public void remove(int idx) throws HCatException {
// contents.remove(idx);
// }
//
// public DefaultHCatRecord(List<Object> list) {
// contents = list;
// }
//
// @Override
// public Object get(int fieldNum) {
// return contents.get(fieldNum);
// }
//
// @Override
// public List<Object> getAll() {
// return contents;
// }
//
// @Override
// public void set(int fieldNum, Object val) {
// contents.set(fieldNum, val);
// }
//
// @Override
// public int size() {
// return contents.size();
// }
//
// @Override
// public void readFields(DataInput in) throws IOException {
//
// contents.clear();
// int len = in.readInt();
// for(int i =0; i < len; i++){
// contents.add(ReaderWriter.readDatum(in));
// }
// }
//
// @Override
// public void write(DataOutput out) throws IOException {
// int sz = size();
// out.writeInt(sz);
// for (int i = 0; i < sz; i++) {
// ReaderWriter.writeDatum(out, contents.get(i));
// }
//
// }
//
// @Override
// public int compareTo(Object that) {
//
// if(that instanceof HCatRecord) {
// HCatRecord other = (HCatRecord)that;
// int mySz = this.size();
// int urSz = other.size();
// if(mySz != urSz) {
// return mySz - urSz;
// } else{
// for (int i = 0; i < mySz;i++) {
// int c = DataType.compare(get(i), other.get(i));
// if (c != 0) {
// return c;
// }
// }
// }
// return 0;
// } else {
// return DataType.compare(this, that);
// }
// }
//
// @Override
// public boolean equals(Object other) {
// return (compareTo(other) == 0);
// }
//
// @Override
// public int hashCode() {
// int hash = 1;
// for (Object o : contents) {
// if (o != null) {
// hash = 31 * hash + o.hashCode();
// }
// }
// return hash;
// }
//
// @Override
// public String toString() {
//
// StringBuilder sb = new StringBuilder();
// for(Object o : contents) {
// sb.append(o+"\t");
// }
// return sb.toString();
// }
//
// @Override
// public Object get(String fieldName, HCatSchema recordSchema) throws HCatException {
// return get(recordSchema.getPosition(fieldName));
// }
//
// @Override
// public void set(String fieldName, HCatSchema recordSchema, Object value) throws HCatException {
// set(recordSchema.getPosition(fieldName),value);
// }
//
// }
| import java.util.Map;
import org.apache.hcatalog.data.DefaultHCatRecord;
import org.apache.hcatalog.data.HCatRecord;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.data;
public class TestDefaultHCatRecord extends TestCase{
public void testRYW() throws IOException{
File f = new File("binary.dat");
f.delete();
f.createNewFile();
f.deleteOnExit();
OutputStream fileOutStream = new FileOutputStream(f);
DataOutput outStream = new DataOutputStream(fileOutStream);
HCatRecord[] recs = getHCatRecords();
for(int i =0; i < recs.length; i++){
recs[i].write(outStream);
}
fileOutStream.flush();
fileOutStream.close();
InputStream fInStream = new FileInputStream(f);
DataInput inpStream = new DataInputStream(fInStream);
for(int i =0; i < recs.length; i++){ | // Path: src/java/org/apache/hcatalog/data/DefaultHCatRecord.java
// public class DefaultHCatRecord extends HCatRecord {
//
// private final List<Object> contents;
//
// public DefaultHCatRecord(){
// contents = new ArrayList<Object>();
// }
//
// public DefaultHCatRecord(int size){
// contents = new ArrayList<Object>(size);
// for(int i=0; i < size; i++){
// contents.add(null);
// }
// }
//
// @Override
// public void remove(int idx) throws HCatException {
// contents.remove(idx);
// }
//
// public DefaultHCatRecord(List<Object> list) {
// contents = list;
// }
//
// @Override
// public Object get(int fieldNum) {
// return contents.get(fieldNum);
// }
//
// @Override
// public List<Object> getAll() {
// return contents;
// }
//
// @Override
// public void set(int fieldNum, Object val) {
// contents.set(fieldNum, val);
// }
//
// @Override
// public int size() {
// return contents.size();
// }
//
// @Override
// public void readFields(DataInput in) throws IOException {
//
// contents.clear();
// int len = in.readInt();
// for(int i =0; i < len; i++){
// contents.add(ReaderWriter.readDatum(in));
// }
// }
//
// @Override
// public void write(DataOutput out) throws IOException {
// int sz = size();
// out.writeInt(sz);
// for (int i = 0; i < sz; i++) {
// ReaderWriter.writeDatum(out, contents.get(i));
// }
//
// }
//
// @Override
// public int compareTo(Object that) {
//
// if(that instanceof HCatRecord) {
// HCatRecord other = (HCatRecord)that;
// int mySz = this.size();
// int urSz = other.size();
// if(mySz != urSz) {
// return mySz - urSz;
// } else{
// for (int i = 0; i < mySz;i++) {
// int c = DataType.compare(get(i), other.get(i));
// if (c != 0) {
// return c;
// }
// }
// }
// return 0;
// } else {
// return DataType.compare(this, that);
// }
// }
//
// @Override
// public boolean equals(Object other) {
// return (compareTo(other) == 0);
// }
//
// @Override
// public int hashCode() {
// int hash = 1;
// for (Object o : contents) {
// if (o != null) {
// hash = 31 * hash + o.hashCode();
// }
// }
// return hash;
// }
//
// @Override
// public String toString() {
//
// StringBuilder sb = new StringBuilder();
// for(Object o : contents) {
// sb.append(o+"\t");
// }
// return sb.toString();
// }
//
// @Override
// public Object get(String fieldName, HCatSchema recordSchema) throws HCatException {
// return get(recordSchema.getPosition(fieldName));
// }
//
// @Override
// public void set(String fieldName, HCatSchema recordSchema, Object value) throws HCatException {
// set(recordSchema.getPosition(fieldName),value);
// }
//
// }
// Path: src/test/org/apache/hcatalog/data/TestDefaultHCatRecord.java
import java.util.Map;
import org.apache.hcatalog.data.DefaultHCatRecord;
import org.apache.hcatalog.data.HCatRecord;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.data;
public class TestDefaultHCatRecord extends TestCase{
public void testRYW() throws IOException{
File f = new File("binary.dat");
f.delete();
f.createNewFile();
f.deleteOnExit();
OutputStream fileOutStream = new FileOutputStream(f);
DataOutput outStream = new DataOutputStream(fileOutStream);
HCatRecord[] recs = getHCatRecords();
for(int i =0; i < recs.length; i++){
recs[i].write(outStream);
}
fileOutStream.flush();
fileOutStream.close();
InputStream fInStream = new FileInputStream(f);
DataInput inpStream = new DataInputStream(fInStream);
for(int i =0; i < recs.length; i++){ | HCatRecord rec = new DefaultHCatRecord(); |
apache/hcatalog | src/java/org/apache/hcatalog/cli/SemanticAnalysis/AddPartitionHook.java | // Path: src/java/org/apache/hcatalog/common/HCatConstants.java
// public final class HCatConstants {
//
// /** The key for the input storage driver class name */
// public static final String HCAT_ISD_CLASS = "hcat.isd";
//
// /** The key for the output storage driver class name */
// public static final String HCAT_OSD_CLASS = "hcat.osd";
//
// public static final String HIVE_RCFILE_IF_CLASS = "org.apache.hadoop.hive.ql.io.RCFileInputFormat";
// public static final String HIVE_RCFILE_OF_CLASS = "org.apache.hadoop.hive.ql.io.RCFileOutputFormat";
// public static final String HCAT_RCFILE_ISD_CLASS = "org.apache.hcatalog.rcfile.RCFileInputDriver";
// public static final String HCAT_RCFILE_OSD_CLASS = "org.apache.hcatalog.rcfile.RCFileOutputDriver";
//
// //The keys used to store info into the job Configuration
// public static final String HCAT_KEY_BASE = "mapreduce.lib.hcat";
//
// public static final String HCAT_KEY_OUTPUT_SCHEMA = HCAT_KEY_BASE + ".output.schema";
//
// public static final String HCAT_KEY_JOB_INFO = HCAT_KEY_BASE + ".job.info";
//
// private HCatConstants() { // restrict instantiation
// }
//
// public static final String HCAT_TABLE_SCHEMA = "hcat.table.schema";
//
// public static final String HCAT_METASTORE_URI = "hcat.metastore.uri";
//
// public static final String HCAT_PERMS = "hcat.perms";
//
// public static final String HCAT_GROUP = "hcat.group";
//
// public static final String HCAT_CREATE_TBL_NAME = "hcat.create.tbl.name";
//
// public static final String HCAT_CREATE_DB_NAME = "hcat.create.db.name";
//
// public static final String HCAT_METASTORE_PRINCIPAL = "hcat.metastore.principal";
//
// // IMPORTANT IMPORTANT IMPORTANT!!!!!
// //The keys used to store info into the job Configuration.
// //If any new keys are added, the HowlStorer needs to be updated. The HowlStorer
// //updates the job configuration in the backend to insert these keys to avoid
// //having to call setOutput from the backend (which would cause a metastore call
// //from the map jobs)
// public static final String HCAT_KEY_OUTPUT_BASE = "mapreduce.lib.hcatoutput";
// public static final String HCAT_KEY_OUTPUT_INFO = HCAT_KEY_OUTPUT_BASE + ".info";
// public static final String HCAT_KEY_HIVE_CONF = HCAT_KEY_OUTPUT_BASE + ".hive.conf";
// public static final String HCAT_KEY_TOKEN_SIGNATURE = HCAT_KEY_OUTPUT_BASE + ".token.sig";
// }
| import java.util.Map;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.AbstractSemanticAnalyzerHook;
import org.apache.hadoop.hive.ql.parse.HiveSemanticAnalyzerHookContext;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hcatalog.common.HCatConstants; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.cli.SemanticAnalysis;
public class AddPartitionHook extends AbstractSemanticAnalyzerHook{
private String tblName, inDriver, outDriver;
@Override
public ASTNode preAnalyze(HiveSemanticAnalyzerHookContext context, ASTNode ast)
throws SemanticException {
Map<String, String> tblProps;
tblName = ast.getChild(0).getText();
try {
tblProps = context.getHive().getTable(tblName).getParameters();
} catch (HiveException he) {
throw new SemanticException(he);
}
| // Path: src/java/org/apache/hcatalog/common/HCatConstants.java
// public final class HCatConstants {
//
// /** The key for the input storage driver class name */
// public static final String HCAT_ISD_CLASS = "hcat.isd";
//
// /** The key for the output storage driver class name */
// public static final String HCAT_OSD_CLASS = "hcat.osd";
//
// public static final String HIVE_RCFILE_IF_CLASS = "org.apache.hadoop.hive.ql.io.RCFileInputFormat";
// public static final String HIVE_RCFILE_OF_CLASS = "org.apache.hadoop.hive.ql.io.RCFileOutputFormat";
// public static final String HCAT_RCFILE_ISD_CLASS = "org.apache.hcatalog.rcfile.RCFileInputDriver";
// public static final String HCAT_RCFILE_OSD_CLASS = "org.apache.hcatalog.rcfile.RCFileOutputDriver";
//
// //The keys used to store info into the job Configuration
// public static final String HCAT_KEY_BASE = "mapreduce.lib.hcat";
//
// public static final String HCAT_KEY_OUTPUT_SCHEMA = HCAT_KEY_BASE + ".output.schema";
//
// public static final String HCAT_KEY_JOB_INFO = HCAT_KEY_BASE + ".job.info";
//
// private HCatConstants() { // restrict instantiation
// }
//
// public static final String HCAT_TABLE_SCHEMA = "hcat.table.schema";
//
// public static final String HCAT_METASTORE_URI = "hcat.metastore.uri";
//
// public static final String HCAT_PERMS = "hcat.perms";
//
// public static final String HCAT_GROUP = "hcat.group";
//
// public static final String HCAT_CREATE_TBL_NAME = "hcat.create.tbl.name";
//
// public static final String HCAT_CREATE_DB_NAME = "hcat.create.db.name";
//
// public static final String HCAT_METASTORE_PRINCIPAL = "hcat.metastore.principal";
//
// // IMPORTANT IMPORTANT IMPORTANT!!!!!
// //The keys used to store info into the job Configuration.
// //If any new keys are added, the HowlStorer needs to be updated. The HowlStorer
// //updates the job configuration in the backend to insert these keys to avoid
// //having to call setOutput from the backend (which would cause a metastore call
// //from the map jobs)
// public static final String HCAT_KEY_OUTPUT_BASE = "mapreduce.lib.hcatoutput";
// public static final String HCAT_KEY_OUTPUT_INFO = HCAT_KEY_OUTPUT_BASE + ".info";
// public static final String HCAT_KEY_HIVE_CONF = HCAT_KEY_OUTPUT_BASE + ".hive.conf";
// public static final String HCAT_KEY_TOKEN_SIGNATURE = HCAT_KEY_OUTPUT_BASE + ".token.sig";
// }
// Path: src/java/org/apache/hcatalog/cli/SemanticAnalysis/AddPartitionHook.java
import java.util.Map;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.AbstractSemanticAnalyzerHook;
import org.apache.hadoop.hive.ql.parse.HiveSemanticAnalyzerHookContext;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hcatalog.common.HCatConstants;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.cli.SemanticAnalysis;
public class AddPartitionHook extends AbstractSemanticAnalyzerHook{
private String tblName, inDriver, outDriver;
@Override
public ASTNode preAnalyze(HiveSemanticAnalyzerHookContext context, ASTNode ast)
throws SemanticException {
Map<String, String> tblProps;
tblName = ast.getChild(0).getText();
try {
tblProps = context.getHive().getTable(tblName).getParameters();
} catch (HiveException he) {
throw new SemanticException(he);
}
| inDriver = tblProps.get(HCatConstants.HCAT_ISD_CLASS); |
apache/hcatalog | src/java/org/apache/hcatalog/data/schema/HCatSchemaUtils.java | // Path: src/java/org/apache/hcatalog/common/HCatException.java
// public class HCatException extends IOException {
//
// private static final long serialVersionUID = 1L;
//
// /** The error type enum for this exception. */
// private final ErrorType errorType;
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// */
// public HCatException(ErrorType errorType) {
// this(errorType, null, null);
// }
//
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, Throwable cause) {
// this(errorType, null, cause);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// */
// public HCatException(ErrorType errorType, String extraMessage) {
// this(errorType, extraMessage, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, String extraMessage, Throwable cause) {
// super(buildErrorMessage(
// errorType,
// extraMessage,
// cause), cause);
// this.errorType = errorType;
// }
//
//
// //TODO : remove default error type constructors after all exceptions
// //are changed to use error types
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// */
// public HCatException(String message) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// * @param cause the cause
// */
// public HCatException(String message, Throwable cause) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, cause);
// }
//
//
// /**
// * Builds the error message string. The error type message is appended with the extra message. If appendCause
// * is true for the error type, then the message of the cause also is added to the message.
// * @param type the error type
// * @param extraMessage the extra message string
// * @param cause the cause for the exception
// * @return the exception message string
// */
// public static String buildErrorMessage(ErrorType type, String extraMessage, Throwable cause) {
//
// //Initial message is just the error type message
// StringBuffer message = new StringBuffer(HCatException.class.getName());
// message.append(" : " + type.getErrorCode());
// message.append(" : " + type.getErrorMessage());
//
// if( extraMessage != null ) {
// //Add the extra message value to buffer
// message.append(" : " + extraMessage);
// }
//
// if( type.appendCauseMessage() ) {
// if( cause != null && cause.getMessage() != null ) {
// //Add the cause message to buffer
// message.append(". Cause : " + cause.toString());
// }
// }
//
// return message.toString();
// }
//
//
// /**
// * Is this a retriable error.
// * @return is it retriable
// */
// public boolean isRetriable() {
// return errorType.isRetriable();
// }
//
// /**
// * Gets the error type.
// * @return the error type enum
// */
// public ErrorType getErrorType() {
// return errorType;
// }
//
// /**
// * Gets the error code.
// * @return the error code
// */
// public int getErrorCode() {
// return errorType.getErrorCode();
// }
//
// /* (non-Javadoc)
// * @see java.lang.Throwable#toString()
// */
// @Override
// public String toString() {
// return getMessage();
// }
//
// }
//
// Path: src/java/org/apache/hcatalog/data/schema/HCatFieldSchema.java
// public enum Type {
// INT,
// TINYINT,
// SMALLINT,
// BIGINT,
// BOOLEAN,
// FLOAT,
// DOUBLE,
// STRING,
// ARRAY,
// MAP,
// STRUCT,
// }
| import org.apache.hcatalog.data.schema.HCatFieldSchema.Type;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Schema;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hcatalog.common.HCatException; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.data.schema;
public class HCatSchemaUtils {
private static HCatSchemaUtils ref = new HCatSchemaUtils();
public static CollectionBuilder getStructSchemaBuilder(){
return ref.new CollectionBuilder();
}
public static CollectionBuilder getListSchemaBuilder(){
return ref.new CollectionBuilder();
}
public static MapBuilder getMapSchemaBuilder(){
return ref.new MapBuilder();
}
public abstract class HCatSchemaBuilder { | // Path: src/java/org/apache/hcatalog/common/HCatException.java
// public class HCatException extends IOException {
//
// private static final long serialVersionUID = 1L;
//
// /** The error type enum for this exception. */
// private final ErrorType errorType;
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// */
// public HCatException(ErrorType errorType) {
// this(errorType, null, null);
// }
//
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, Throwable cause) {
// this(errorType, null, cause);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// */
// public HCatException(ErrorType errorType, String extraMessage) {
// this(errorType, extraMessage, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, String extraMessage, Throwable cause) {
// super(buildErrorMessage(
// errorType,
// extraMessage,
// cause), cause);
// this.errorType = errorType;
// }
//
//
// //TODO : remove default error type constructors after all exceptions
// //are changed to use error types
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// */
// public HCatException(String message) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// * @param cause the cause
// */
// public HCatException(String message, Throwable cause) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, cause);
// }
//
//
// /**
// * Builds the error message string. The error type message is appended with the extra message. If appendCause
// * is true for the error type, then the message of the cause also is added to the message.
// * @param type the error type
// * @param extraMessage the extra message string
// * @param cause the cause for the exception
// * @return the exception message string
// */
// public static String buildErrorMessage(ErrorType type, String extraMessage, Throwable cause) {
//
// //Initial message is just the error type message
// StringBuffer message = new StringBuffer(HCatException.class.getName());
// message.append(" : " + type.getErrorCode());
// message.append(" : " + type.getErrorMessage());
//
// if( extraMessage != null ) {
// //Add the extra message value to buffer
// message.append(" : " + extraMessage);
// }
//
// if( type.appendCauseMessage() ) {
// if( cause != null && cause.getMessage() != null ) {
// //Add the cause message to buffer
// message.append(". Cause : " + cause.toString());
// }
// }
//
// return message.toString();
// }
//
//
// /**
// * Is this a retriable error.
// * @return is it retriable
// */
// public boolean isRetriable() {
// return errorType.isRetriable();
// }
//
// /**
// * Gets the error type.
// * @return the error type enum
// */
// public ErrorType getErrorType() {
// return errorType;
// }
//
// /**
// * Gets the error code.
// * @return the error code
// */
// public int getErrorCode() {
// return errorType.getErrorCode();
// }
//
// /* (non-Javadoc)
// * @see java.lang.Throwable#toString()
// */
// @Override
// public String toString() {
// return getMessage();
// }
//
// }
//
// Path: src/java/org/apache/hcatalog/data/schema/HCatFieldSchema.java
// public enum Type {
// INT,
// TINYINT,
// SMALLINT,
// BIGINT,
// BOOLEAN,
// FLOAT,
// DOUBLE,
// STRING,
// ARRAY,
// MAP,
// STRUCT,
// }
// Path: src/java/org/apache/hcatalog/data/schema/HCatSchemaUtils.java
import org.apache.hcatalog.data.schema.HCatFieldSchema.Type;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Schema;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hcatalog.common.HCatException;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hcatalog.data.schema;
public class HCatSchemaUtils {
private static HCatSchemaUtils ref = new HCatSchemaUtils();
public static CollectionBuilder getStructSchemaBuilder(){
return ref.new CollectionBuilder();
}
public static CollectionBuilder getListSchemaBuilder(){
return ref.new CollectionBuilder();
}
public static MapBuilder getMapSchemaBuilder(){
return ref.new MapBuilder();
}
public abstract class HCatSchemaBuilder { | public abstract HCatSchema build() throws HCatException; |
apache/hcatalog | src/java/org/apache/hcatalog/data/schema/HCatSchemaUtils.java | // Path: src/java/org/apache/hcatalog/common/HCatException.java
// public class HCatException extends IOException {
//
// private static final long serialVersionUID = 1L;
//
// /** The error type enum for this exception. */
// private final ErrorType errorType;
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// */
// public HCatException(ErrorType errorType) {
// this(errorType, null, null);
// }
//
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, Throwable cause) {
// this(errorType, null, cause);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// */
// public HCatException(ErrorType errorType, String extraMessage) {
// this(errorType, extraMessage, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, String extraMessage, Throwable cause) {
// super(buildErrorMessage(
// errorType,
// extraMessage,
// cause), cause);
// this.errorType = errorType;
// }
//
//
// //TODO : remove default error type constructors after all exceptions
// //are changed to use error types
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// */
// public HCatException(String message) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// * @param cause the cause
// */
// public HCatException(String message, Throwable cause) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, cause);
// }
//
//
// /**
// * Builds the error message string. The error type message is appended with the extra message. If appendCause
// * is true for the error type, then the message of the cause also is added to the message.
// * @param type the error type
// * @param extraMessage the extra message string
// * @param cause the cause for the exception
// * @return the exception message string
// */
// public static String buildErrorMessage(ErrorType type, String extraMessage, Throwable cause) {
//
// //Initial message is just the error type message
// StringBuffer message = new StringBuffer(HCatException.class.getName());
// message.append(" : " + type.getErrorCode());
// message.append(" : " + type.getErrorMessage());
//
// if( extraMessage != null ) {
// //Add the extra message value to buffer
// message.append(" : " + extraMessage);
// }
//
// if( type.appendCauseMessage() ) {
// if( cause != null && cause.getMessage() != null ) {
// //Add the cause message to buffer
// message.append(". Cause : " + cause.toString());
// }
// }
//
// return message.toString();
// }
//
//
// /**
// * Is this a retriable error.
// * @return is it retriable
// */
// public boolean isRetriable() {
// return errorType.isRetriable();
// }
//
// /**
// * Gets the error type.
// * @return the error type enum
// */
// public ErrorType getErrorType() {
// return errorType;
// }
//
// /**
// * Gets the error code.
// * @return the error code
// */
// public int getErrorCode() {
// return errorType.getErrorCode();
// }
//
// /* (non-Javadoc)
// * @see java.lang.Throwable#toString()
// */
// @Override
// public String toString() {
// return getMessage();
// }
//
// }
//
// Path: src/java/org/apache/hcatalog/data/schema/HCatFieldSchema.java
// public enum Type {
// INT,
// TINYINT,
// SMALLINT,
// BIGINT,
// BOOLEAN,
// FLOAT,
// DOUBLE,
// STRING,
// ARRAY,
// MAP,
// STRUCT,
// }
| import org.apache.hcatalog.data.schema.HCatFieldSchema.Type;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Schema;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hcatalog.common.HCatException; |
public abstract class HCatSchemaBuilder {
public abstract HCatSchema build() throws HCatException;
}
public class CollectionBuilder extends HCatSchemaBuilder { // for STRUCTS(multiple-add-calls) and LISTS(single-add-call)
List<HCatFieldSchema> fieldSchemas = null;
CollectionBuilder(){
fieldSchemas = new ArrayList<HCatFieldSchema>();
}
public CollectionBuilder addField(FieldSchema fieldSchema) throws HCatException{
return this.addField(getHCatFieldSchema(fieldSchema));
}
public CollectionBuilder addField(HCatFieldSchema fieldColumnSchema){
fieldSchemas.add(fieldColumnSchema);
return this;
}
@Override
public HCatSchema build() throws HCatException{
return new HCatSchema(fieldSchemas);
}
}
public class MapBuilder extends HCatSchemaBuilder {
| // Path: src/java/org/apache/hcatalog/common/HCatException.java
// public class HCatException extends IOException {
//
// private static final long serialVersionUID = 1L;
//
// /** The error type enum for this exception. */
// private final ErrorType errorType;
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// */
// public HCatException(ErrorType errorType) {
// this(errorType, null, null);
// }
//
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, Throwable cause) {
// this(errorType, null, cause);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// */
// public HCatException(ErrorType errorType, String extraMessage) {
// this(errorType, extraMessage, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param errorType the error type
// * @param extraMessage extra messages to add to the message string
// * @param cause the cause
// */
// public HCatException(ErrorType errorType, String extraMessage, Throwable cause) {
// super(buildErrorMessage(
// errorType,
// extraMessage,
// cause), cause);
// this.errorType = errorType;
// }
//
//
// //TODO : remove default error type constructors after all exceptions
// //are changed to use error types
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// */
// public HCatException(String message) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, null);
// }
//
// /**
// * Instantiates a new howl exception.
// * @param message the error message
// * @param cause the cause
// */
// public HCatException(String message, Throwable cause) {
// this(ErrorType.ERROR_INTERNAL_EXCEPTION, message, cause);
// }
//
//
// /**
// * Builds the error message string. The error type message is appended with the extra message. If appendCause
// * is true for the error type, then the message of the cause also is added to the message.
// * @param type the error type
// * @param extraMessage the extra message string
// * @param cause the cause for the exception
// * @return the exception message string
// */
// public static String buildErrorMessage(ErrorType type, String extraMessage, Throwable cause) {
//
// //Initial message is just the error type message
// StringBuffer message = new StringBuffer(HCatException.class.getName());
// message.append(" : " + type.getErrorCode());
// message.append(" : " + type.getErrorMessage());
//
// if( extraMessage != null ) {
// //Add the extra message value to buffer
// message.append(" : " + extraMessage);
// }
//
// if( type.appendCauseMessage() ) {
// if( cause != null && cause.getMessage() != null ) {
// //Add the cause message to buffer
// message.append(". Cause : " + cause.toString());
// }
// }
//
// return message.toString();
// }
//
//
// /**
// * Is this a retriable error.
// * @return is it retriable
// */
// public boolean isRetriable() {
// return errorType.isRetriable();
// }
//
// /**
// * Gets the error type.
// * @return the error type enum
// */
// public ErrorType getErrorType() {
// return errorType;
// }
//
// /**
// * Gets the error code.
// * @return the error code
// */
// public int getErrorCode() {
// return errorType.getErrorCode();
// }
//
// /* (non-Javadoc)
// * @see java.lang.Throwable#toString()
// */
// @Override
// public String toString() {
// return getMessage();
// }
//
// }
//
// Path: src/java/org/apache/hcatalog/data/schema/HCatFieldSchema.java
// public enum Type {
// INT,
// TINYINT,
// SMALLINT,
// BIGINT,
// BOOLEAN,
// FLOAT,
// DOUBLE,
// STRING,
// ARRAY,
// MAP,
// STRUCT,
// }
// Path: src/java/org/apache/hcatalog/data/schema/HCatSchemaUtils.java
import org.apache.hcatalog.data.schema.HCatFieldSchema.Type;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Schema;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hcatalog.common.HCatException;
public abstract class HCatSchemaBuilder {
public abstract HCatSchema build() throws HCatException;
}
public class CollectionBuilder extends HCatSchemaBuilder { // for STRUCTS(multiple-add-calls) and LISTS(single-add-call)
List<HCatFieldSchema> fieldSchemas = null;
CollectionBuilder(){
fieldSchemas = new ArrayList<HCatFieldSchema>();
}
public CollectionBuilder addField(FieldSchema fieldSchema) throws HCatException{
return this.addField(getHCatFieldSchema(fieldSchema));
}
public CollectionBuilder addField(HCatFieldSchema fieldColumnSchema){
fieldSchemas.add(fieldColumnSchema);
return this;
}
@Override
public HCatSchema build() throws HCatException{
return new HCatSchema(fieldSchemas);
}
}
public class MapBuilder extends HCatSchemaBuilder {
| Type keyType = null; |
googleads/googleads-mobile-android-examples | java/admob/AppOpenExample/app/src/main/java/com/google/android/gms/example/appopendemo/SplashActivity.java | // Path: java/admanager/AppOpenExample/app/src/main/java/com/google/android/gms/example/appopendemo/MyApplication.java
// public interface OnShowAdCompleteListener {
// void onShowAdComplete();
// }
| import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.example.appopendemo.MyApplication.OnShowAdCompleteListener; | private void createTimer(long seconds) {
final TextView counterTextView = findViewById(R.id.timer);
CountDownTimer countDownTimer =
new CountDownTimer(seconds * 1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
secondsRemaining = ((millisUntilFinished / 1000) + 1);
counterTextView.setText("App is done loading in: " + secondsRemaining);
}
@Override
public void onFinish() {
secondsRemaining = 0;
counterTextView.setText("Done.");
Application application = getApplication();
// If the application is not an instance of MyApplication, log an error message and
// start the MainActivity without showing the app open ad.
if (!(application instanceof MyApplication)) {
Log.e(LOG_TAG, "Failed to cast application to MyApplication.");
startMainActivity();
return;
}
// Show the app open ad.
((MyApplication) application)
.showAdIfAvailable(
SplashActivity.this, | // Path: java/admanager/AppOpenExample/app/src/main/java/com/google/android/gms/example/appopendemo/MyApplication.java
// public interface OnShowAdCompleteListener {
// void onShowAdComplete();
// }
// Path: java/admob/AppOpenExample/app/src/main/java/com/google/android/gms/example/appopendemo/SplashActivity.java
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.example.appopendemo.MyApplication.OnShowAdCompleteListener;
private void createTimer(long seconds) {
final TextView counterTextView = findViewById(R.id.timer);
CountDownTimer countDownTimer =
new CountDownTimer(seconds * 1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
secondsRemaining = ((millisUntilFinished / 1000) + 1);
counterTextView.setText("App is done loading in: " + secondsRemaining);
}
@Override
public void onFinish() {
secondsRemaining = 0;
counterTextView.setText("Done.");
Application application = getApplication();
// If the application is not an instance of MyApplication, log an error message and
// start the MainActivity without showing the app open ad.
if (!(application instanceof MyApplication)) {
Log.e(LOG_TAG, "Failed to cast application to MyApplication.");
startMainActivity();
return;
}
// Show the app open ad.
((MyApplication) application)
.showAdIfAvailable(
SplashActivity.this, | new OnShowAdCompleteListener() { |
fabriziocucci/yacl4j | yacl4j-http/src/test/java/org/yacl4j/http/HttpsTest.java | // Path: yacl4j-core/src/main/java/com/yacl4j/core/ConfigurationBuilder.java
// public class ConfigurationBuilder {
//
// private final List<ConfigurationSource> configurationSources;
// private PlaceholderResolver placeholderResolver;
// private Optional<ValueDecoder> valueDecoder;
//
// private ConfigurationBuilder() {
// this.configurationSources = new LinkedList<>();
// this.placeholderResolver = new NonRecursivePlaceholderResolver();
// this.valueDecoder = Optional.empty();
// }
//
// public static ConfigurationBuilder newBuilder() {
// return new ConfigurationBuilder();
// }
//
// public ConfigurationBuilder placeholderResolver(PlaceholderResolver placeholderResolver) {
// this.placeholderResolver = placeholderResolver;
// return this;
// }
//
// public ConfigurationBuilder valueDecoder(ValueDecoder valueDecoder) {
// this.valueDecoder = Optional.of(valueDecoder);
// return this;
// }
//
// public ConfigurationSourceBuilder source() {
// return new ConfigurationSourceBuilder(this);
// }
//
// public ConfigurationBuilder source(ConfigurationSource configurationSource) {
// this.configurationSources.add(configurationSource);
// return this;
// }
//
// public OptionalConfigurationSourceBuilder optionalSource() {
// return new OptionalConfigurationSourceBuilder(this);
// }
//
// public ConfigurationBuilder optionalSource(ConfigurationSource configurationSource) {
// return source(OptionalConfigurationSource.build(configurationSource));
// }
//
// public ConfigurationBuilder optionalSource(Supplier<ConfigurationSource> configurationSourceFactory) {
// return source(OptionalConfigurationSource.build(configurationSourceFactory));
// }
//
// public <T> T build(Class<T> configurationClass) {
// JsonNode configuration = mergeConfigurationSources();
// this.placeholderResolver.resolvePlaceholders(configuration);
// this.valueDecoder.ifPresent(valueDecoder -> valueDecoder.decodeValues(configuration));
// return ConfigurationUtils.toValue(configuration, configurationClass);
// }
//
// private JsonNode mergeConfigurationSources() {
// return configurationSources.stream()
// .map(ConfigurationSource::getConfiguration)
// .reduce(ConfigurationUtils.emptyConfiguration(), ConfigurationUtils::merge);
// }
//
// }
| import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import javax.net.ssl.SSLContext;
import org.glassfish.jersey.SslConfigurator;
import org.junit.ClassRule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.yacl4j.core.ConfigurationBuilder;
import yacl4j.repackaged.com.fasterxml.jackson.databind.JsonNode; | package org.yacl4j.http;
public class HttpsTest {
@ClassRule
public static final WireMockRule WIRE_MOCK_RULE = new WireMockRule(wireMockConfig()
.httpsPort(8443)
.keystorePath("src/test/resources/test.jks")
.keystorePassword("changeit"));
@Test
public void testThatYamlConfigurationIsRetrieved() {
| // Path: yacl4j-core/src/main/java/com/yacl4j/core/ConfigurationBuilder.java
// public class ConfigurationBuilder {
//
// private final List<ConfigurationSource> configurationSources;
// private PlaceholderResolver placeholderResolver;
// private Optional<ValueDecoder> valueDecoder;
//
// private ConfigurationBuilder() {
// this.configurationSources = new LinkedList<>();
// this.placeholderResolver = new NonRecursivePlaceholderResolver();
// this.valueDecoder = Optional.empty();
// }
//
// public static ConfigurationBuilder newBuilder() {
// return new ConfigurationBuilder();
// }
//
// public ConfigurationBuilder placeholderResolver(PlaceholderResolver placeholderResolver) {
// this.placeholderResolver = placeholderResolver;
// return this;
// }
//
// public ConfigurationBuilder valueDecoder(ValueDecoder valueDecoder) {
// this.valueDecoder = Optional.of(valueDecoder);
// return this;
// }
//
// public ConfigurationSourceBuilder source() {
// return new ConfigurationSourceBuilder(this);
// }
//
// public ConfigurationBuilder source(ConfigurationSource configurationSource) {
// this.configurationSources.add(configurationSource);
// return this;
// }
//
// public OptionalConfigurationSourceBuilder optionalSource() {
// return new OptionalConfigurationSourceBuilder(this);
// }
//
// public ConfigurationBuilder optionalSource(ConfigurationSource configurationSource) {
// return source(OptionalConfigurationSource.build(configurationSource));
// }
//
// public ConfigurationBuilder optionalSource(Supplier<ConfigurationSource> configurationSourceFactory) {
// return source(OptionalConfigurationSource.build(configurationSourceFactory));
// }
//
// public <T> T build(Class<T> configurationClass) {
// JsonNode configuration = mergeConfigurationSources();
// this.placeholderResolver.resolvePlaceholders(configuration);
// this.valueDecoder.ifPresent(valueDecoder -> valueDecoder.decodeValues(configuration));
// return ConfigurationUtils.toValue(configuration, configurationClass);
// }
//
// private JsonNode mergeConfigurationSources() {
// return configurationSources.stream()
// .map(ConfigurationSource::getConfiguration)
// .reduce(ConfigurationUtils.emptyConfiguration(), ConfigurationUtils::merge);
// }
//
// }
// Path: yacl4j-http/src/test/java/org/yacl4j/http/HttpsTest.java
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import javax.net.ssl.SSLContext;
import org.glassfish.jersey.SslConfigurator;
import org.junit.ClassRule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.yacl4j.core.ConfigurationBuilder;
import yacl4j.repackaged.com.fasterxml.jackson.databind.JsonNode;
package org.yacl4j.http;
public class HttpsTest {
@ClassRule
public static final WireMockRule WIRE_MOCK_RULE = new WireMockRule(wireMockConfig()
.httpsPort(8443)
.keystorePath("src/test/resources/test.jks")
.keystorePassword("changeit"));
@Test
public void testThatYamlConfigurationIsRetrieved() {
| JsonNode configuration = ConfigurationBuilder.newBuilder() |
fabriziocucci/yacl4j | yacl4j-http/src/test/java/org/yacl4j/http/HttpTest.java | // Path: yacl4j-core/src/main/java/com/yacl4j/core/ConfigurationBuilder.java
// public class ConfigurationBuilder {
//
// private final List<ConfigurationSource> configurationSources;
// private PlaceholderResolver placeholderResolver;
// private Optional<ValueDecoder> valueDecoder;
//
// private ConfigurationBuilder() {
// this.configurationSources = new LinkedList<>();
// this.placeholderResolver = new NonRecursivePlaceholderResolver();
// this.valueDecoder = Optional.empty();
// }
//
// public static ConfigurationBuilder newBuilder() {
// return new ConfigurationBuilder();
// }
//
// public ConfigurationBuilder placeholderResolver(PlaceholderResolver placeholderResolver) {
// this.placeholderResolver = placeholderResolver;
// return this;
// }
//
// public ConfigurationBuilder valueDecoder(ValueDecoder valueDecoder) {
// this.valueDecoder = Optional.of(valueDecoder);
// return this;
// }
//
// public ConfigurationSourceBuilder source() {
// return new ConfigurationSourceBuilder(this);
// }
//
// public ConfigurationBuilder source(ConfigurationSource configurationSource) {
// this.configurationSources.add(configurationSource);
// return this;
// }
//
// public OptionalConfigurationSourceBuilder optionalSource() {
// return new OptionalConfigurationSourceBuilder(this);
// }
//
// public ConfigurationBuilder optionalSource(ConfigurationSource configurationSource) {
// return source(OptionalConfigurationSource.build(configurationSource));
// }
//
// public ConfigurationBuilder optionalSource(Supplier<ConfigurationSource> configurationSourceFactory) {
// return source(OptionalConfigurationSource.build(configurationSourceFactory));
// }
//
// public <T> T build(Class<T> configurationClass) {
// JsonNode configuration = mergeConfigurationSources();
// this.placeholderResolver.resolvePlaceholders(configuration);
// this.valueDecoder.ifPresent(valueDecoder -> valueDecoder.decodeValues(configuration));
// return ConfigurationUtils.toValue(configuration, configurationClass);
// }
//
// private JsonNode mergeConfigurationSources() {
// return configurationSources.stream()
// .map(ConfigurationSource::getConfiguration)
// .reduce(ConfigurationUtils.emptyConfiguration(), ConfigurationUtils::merge);
// }
//
// }
| import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.ClassRule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.yacl4j.core.ConfigurationBuilder;
import yacl4j.repackaged.com.fasterxml.jackson.databind.JsonNode; | package org.yacl4j.http;
public class HttpTest {
@ClassRule
public static final WireMockRule WIRE_MOCK_RULE = new WireMockRule(8080);
@Test
public void testThatYamlConfigurationIsRetrieved() {
| // Path: yacl4j-core/src/main/java/com/yacl4j/core/ConfigurationBuilder.java
// public class ConfigurationBuilder {
//
// private final List<ConfigurationSource> configurationSources;
// private PlaceholderResolver placeholderResolver;
// private Optional<ValueDecoder> valueDecoder;
//
// private ConfigurationBuilder() {
// this.configurationSources = new LinkedList<>();
// this.placeholderResolver = new NonRecursivePlaceholderResolver();
// this.valueDecoder = Optional.empty();
// }
//
// public static ConfigurationBuilder newBuilder() {
// return new ConfigurationBuilder();
// }
//
// public ConfigurationBuilder placeholderResolver(PlaceholderResolver placeholderResolver) {
// this.placeholderResolver = placeholderResolver;
// return this;
// }
//
// public ConfigurationBuilder valueDecoder(ValueDecoder valueDecoder) {
// this.valueDecoder = Optional.of(valueDecoder);
// return this;
// }
//
// public ConfigurationSourceBuilder source() {
// return new ConfigurationSourceBuilder(this);
// }
//
// public ConfigurationBuilder source(ConfigurationSource configurationSource) {
// this.configurationSources.add(configurationSource);
// return this;
// }
//
// public OptionalConfigurationSourceBuilder optionalSource() {
// return new OptionalConfigurationSourceBuilder(this);
// }
//
// public ConfigurationBuilder optionalSource(ConfigurationSource configurationSource) {
// return source(OptionalConfigurationSource.build(configurationSource));
// }
//
// public ConfigurationBuilder optionalSource(Supplier<ConfigurationSource> configurationSourceFactory) {
// return source(OptionalConfigurationSource.build(configurationSourceFactory));
// }
//
// public <T> T build(Class<T> configurationClass) {
// JsonNode configuration = mergeConfigurationSources();
// this.placeholderResolver.resolvePlaceholders(configuration);
// this.valueDecoder.ifPresent(valueDecoder -> valueDecoder.decodeValues(configuration));
// return ConfigurationUtils.toValue(configuration, configurationClass);
// }
//
// private JsonNode mergeConfigurationSources() {
// return configurationSources.stream()
// .map(ConfigurationSource::getConfiguration)
// .reduce(ConfigurationUtils.emptyConfiguration(), ConfigurationUtils::merge);
// }
//
// }
// Path: yacl4j-http/src/test/java/org/yacl4j/http/HttpTest.java
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.ClassRule;
import org.junit.Test;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.yacl4j.core.ConfigurationBuilder;
import yacl4j.repackaged.com.fasterxml.jackson.databind.JsonNode;
package org.yacl4j.http;
public class HttpTest {
@ClassRule
public static final WireMockRule WIRE_MOCK_RULE = new WireMockRule(8080);
@Test
public void testThatYamlConfigurationIsRetrieved() {
| JsonNode configuration = ConfigurationBuilder.newBuilder() |
fabriziocucci/yacl4j | yacl4j-core/src/test/java/com/yacl4j/core/ConfigurationBuilderWithUserDefinedInterfaceTest.java | // Path: yacl4j-core/src/test/java/com/yacl4j/test/TestUtils.java
// public class TestUtils {
//
// public static File createConfigurationFile(String configuration, String fileExtension) throws IOException {
// File configurationFile = File.createTempFile("application", fileExtension);
// try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(configurationFile))) {
// bufferedWriter.write(configuration);
// return configurationFile;
// }
// }
//
// }
//
// Path: yacl4j-core/src/test/java/com/yacl4j/core/ConfigurationBuilderWithUserDefinedInterfaceTest.java
// static interface NestedApplicationConfiguration {
//
// public int getIntField();
// public boolean getBooleanField();
// public String getStringField();
//
// }
| import static com.yacl4j.test.TestUtils.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.Test;
import com.yacl4j.core.ConfigurationBuilderWithUserDefinedInterfaceTest.ApplicationConfiguration.NestedApplicationConfiguration; | package com.yacl4j.core;
public class ConfigurationBuilderWithUserDefinedInterfaceTest {
public static interface ApplicationConfiguration {
public int getIntField();
public boolean getBooleanField();
public String getStringField();
| // Path: yacl4j-core/src/test/java/com/yacl4j/test/TestUtils.java
// public class TestUtils {
//
// public static File createConfigurationFile(String configuration, String fileExtension) throws IOException {
// File configurationFile = File.createTempFile("application", fileExtension);
// try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(configurationFile))) {
// bufferedWriter.write(configuration);
// return configurationFile;
// }
// }
//
// }
//
// Path: yacl4j-core/src/test/java/com/yacl4j/core/ConfigurationBuilderWithUserDefinedInterfaceTest.java
// static interface NestedApplicationConfiguration {
//
// public int getIntField();
// public boolean getBooleanField();
// public String getStringField();
//
// }
// Path: yacl4j-core/src/test/java/com/yacl4j/core/ConfigurationBuilderWithUserDefinedInterfaceTest.java
import static com.yacl4j.test.TestUtils.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.Test;
import com.yacl4j.core.ConfigurationBuilderWithUserDefinedInterfaceTest.ApplicationConfiguration.NestedApplicationConfiguration;
package com.yacl4j.core;
public class ConfigurationBuilderWithUserDefinedInterfaceTest {
public static interface ApplicationConfiguration {
public int getIntField();
public boolean getBooleanField();
public String getStringField();
| public NestedApplicationConfiguration getNestedApplicationConfiguration(); |
fabriziocucci/yacl4j | yacl4j-core/src/test/java/com/yacl4j/core/ConfigurationBuilderWithSingleOptionalSourceTest.java | // Path: yacl4j-core/src/main/java/com/yacl4j/core/source/optional/ConfigurationSourceNotAvailableException.java
// public class ConfigurationSourceNotAvailableException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ConfigurationSourceNotAvailableException() {
// super();
// }
//
// public ConfigurationSourceNotAvailableException(String message) {
// super(message);
// }
//
// public ConfigurationSourceNotAvailableException(Throwable cause) {
// super(cause);
// }
//
// public ConfigurationSourceNotAvailableException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ConfigurationSourceNotAvailableException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
//
// }
| import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.io.File;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.yacl4j.core.source.optional.ConfigurationSourceNotAvailableException;
import mockit.integration.junit4.JMockit;
import yacl4j.repackaged.com.fasterxml.jackson.databind.JsonNode; |
@Test
public void testConfigurationBuilderWhenOptionalJsonFileFromPathDoesNotExists() {
JsonNode configuration = ConfigurationBuilder.newBuilder()
.optionalSource().fromFileOnPath("i-dont-exist.json")
.build(JsonNode.class);
assertThat(configuration, is(notNullValue()));
assertThat(configuration.fields().hasNext(), is(false));
}
@Test
public void testConfigurationBuilderWhenOptionalPropertiesFileFromPathDoesNotExists() {
JsonNode configuration = ConfigurationBuilder.newBuilder()
.optionalSource().fromFileOnPath("i-dont-exist.properties")
.build(JsonNode.class);
assertThat(configuration, is(notNullValue()));
assertThat(configuration.fields().hasNext(), is(false));
}
/////////////////////////////////////////
// optional eager configuration source //
/////////////////////////////////////////
private static class EagerConfigurationSource implements ConfigurationSource {
private EagerConfigurationSource() { | // Path: yacl4j-core/src/main/java/com/yacl4j/core/source/optional/ConfigurationSourceNotAvailableException.java
// public class ConfigurationSourceNotAvailableException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ConfigurationSourceNotAvailableException() {
// super();
// }
//
// public ConfigurationSourceNotAvailableException(String message) {
// super(message);
// }
//
// public ConfigurationSourceNotAvailableException(Throwable cause) {
// super(cause);
// }
//
// public ConfigurationSourceNotAvailableException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ConfigurationSourceNotAvailableException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
//
// }
// Path: yacl4j-core/src/test/java/com/yacl4j/core/ConfigurationBuilderWithSingleOptionalSourceTest.java
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.io.File;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.yacl4j.core.source.optional.ConfigurationSourceNotAvailableException;
import mockit.integration.junit4.JMockit;
import yacl4j.repackaged.com.fasterxml.jackson.databind.JsonNode;
@Test
public void testConfigurationBuilderWhenOptionalJsonFileFromPathDoesNotExists() {
JsonNode configuration = ConfigurationBuilder.newBuilder()
.optionalSource().fromFileOnPath("i-dont-exist.json")
.build(JsonNode.class);
assertThat(configuration, is(notNullValue()));
assertThat(configuration.fields().hasNext(), is(false));
}
@Test
public void testConfigurationBuilderWhenOptionalPropertiesFileFromPathDoesNotExists() {
JsonNode configuration = ConfigurationBuilder.newBuilder()
.optionalSource().fromFileOnPath("i-dont-exist.properties")
.build(JsonNode.class);
assertThat(configuration, is(notNullValue()));
assertThat(configuration.fields().hasNext(), is(false));
}
/////////////////////////////////////////
// optional eager configuration source //
/////////////////////////////////////////
private static class EagerConfigurationSource implements ConfigurationSource {
private EagerConfigurationSource() { | throw new ConfigurationSourceNotAvailableException(); |
fabriziocucci/yacl4j | yacl4j-core/src/main/java/com/yacl4j/core/placeholder/NonRecursivePlaceholderResolver.java | // Path: yacl4j-core/src/main/java/com/yacl4j/core/AbstractNodeTransformer.java
// public abstract class AbstractNodeTransformer {
//
// protected void transform(JsonNode configuration) {
// transform(configuration, configuration, MissingNode.getInstance(), "");
// }
//
// private void transform(JsonNode root, JsonNode currentNode, JsonNode parentNode, String fieldOrIndexInParent) {
// switch (currentNode.getNodeType()) {
// case OBJECT: transformObjectNode(root, currentNode, parentNode); break;
// case ARRAY: transformArrayNode(root, currentNode, parentNode); break;
// default: transformValueNodeBasedOnParent(root, currentNode, parentNode, fieldOrIndexInParent); break;
// }
// }
//
// private void transformObjectNode(JsonNode root, JsonNode currentNode, JsonNode parentNode) {
// Iterator<Entry<String, JsonNode>> fields = currentNode.fields();
// while (fields.hasNext()) {
// Entry<String, JsonNode> childEntry = fields.next();
// transform(root, childEntry.getValue(), currentNode, childEntry.getKey());
// }
// }
//
// private void transformArrayNode(JsonNode root, JsonNode currentNode, JsonNode parentNode) {
// for (int i = 0; i < currentNode.size(); i++) {
// transform(root, currentNode.get(i), currentNode, Integer.toString(i));
// }
// }
//
// private void transformValueNodeBasedOnParent(JsonNode root, JsonNode currentNode, JsonNode parentNode, String fieldOrIndexInParent) {
// switch (parentNode.getNodeType()) {
// case OBJECT: ((ObjectNode)parentNode).set(fieldOrIndexInParent, transformValueNode(root, currentNode)); break;
// case ARRAY: ((ArrayNode)parentNode).set(Integer.valueOf(fieldOrIndexInParent), transformValueNode(root, currentNode)); break;
// default: break;
// }
// }
//
// abstract protected JsonNode transformValueNode(JsonNode root, JsonNode currentNode);
//
// }
//
// Path: yacl4j-core/src/main/java/com/yacl4j/core/PlaceholderResolver.java
// public interface PlaceholderResolver {
//
// void resolvePlaceholders(JsonNode configuration);
//
// }
//
// Path: yacl4j-core/src/main/java/com/yacl4j/core/util/JsonPointerUtils.java
// public class JsonPointerUtils {
//
// private JsonPointerUtils() { }
//
// private static final JsonPointer EMPTY_JSON_POINTER = JsonPointer.compile("");
//
// public static JsonPointer fromProperty(String property) {
// if (property.startsWith("/") || property.isEmpty()) {
// return JsonPointer.compile(property);
// } else {
// return JsonPointer.compile("/" + property);
// }
// }
//
// public static List<JsonPointer> heads(JsonPointer jsonPointer) {
// LinkedList<JsonPointer> heads = new LinkedList<>();
// while (!jsonPointer.equals(EMPTY_JSON_POINTER)) {
// jsonPointer = jsonPointer.head();
// heads.addFirst(jsonPointer);
// }
// return heads;
// }
//
// }
| import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.yacl4j.core.AbstractNodeTransformer;
import com.yacl4j.core.PlaceholderResolver;
import com.yacl4j.core.util.JsonPointerUtils;
import yacl4j.repackaged.com.fasterxml.jackson.core.JsonPointer;
import yacl4j.repackaged.com.fasterxml.jackson.databind.JsonNode;
import yacl4j.repackaged.com.fasterxml.jackson.databind.node.TextNode; | } else {
return replacementNode;
}
}
private JsonNode resolveValueNodeByDereferencingValueNodes(JsonNode root, JsonNode currentNode, List<JsonPointerPlaceholder> matches) {
String resolvedValue = currentNode.asText();
for (JsonPointerPlaceholder match : matches) {
JsonNode replacementNode = root.at(match.jsonPointer);
if (!replacementNode.isMissingNode() && !replacementNode.isContainerNode()) {
resolvedValue = resolvedValue.replaceAll(Pattern.quote(match.placeholder), Matcher.quoteReplacement(replacementNode.asText()));
}
}
return TextNode.valueOf(resolvedValue);
}
private static class JsonPointerPlaceholder {
private String placeholder;
private JsonPointer jsonPointer;
private JsonPointerPlaceholder(String placeholder, JsonPointer jsonPointer) {
this.placeholder = placeholder;
this.jsonPointer = jsonPointer;
}
private static Optional<JsonPointerPlaceholder> parseJsonPointerPlaceholder(Matcher matcher) {
if (matcher.groupCount() == 2) {
String placeholder = matcher.group(1);
String property = matcher.group(2); | // Path: yacl4j-core/src/main/java/com/yacl4j/core/AbstractNodeTransformer.java
// public abstract class AbstractNodeTransformer {
//
// protected void transform(JsonNode configuration) {
// transform(configuration, configuration, MissingNode.getInstance(), "");
// }
//
// private void transform(JsonNode root, JsonNode currentNode, JsonNode parentNode, String fieldOrIndexInParent) {
// switch (currentNode.getNodeType()) {
// case OBJECT: transformObjectNode(root, currentNode, parentNode); break;
// case ARRAY: transformArrayNode(root, currentNode, parentNode); break;
// default: transformValueNodeBasedOnParent(root, currentNode, parentNode, fieldOrIndexInParent); break;
// }
// }
//
// private void transformObjectNode(JsonNode root, JsonNode currentNode, JsonNode parentNode) {
// Iterator<Entry<String, JsonNode>> fields = currentNode.fields();
// while (fields.hasNext()) {
// Entry<String, JsonNode> childEntry = fields.next();
// transform(root, childEntry.getValue(), currentNode, childEntry.getKey());
// }
// }
//
// private void transformArrayNode(JsonNode root, JsonNode currentNode, JsonNode parentNode) {
// for (int i = 0; i < currentNode.size(); i++) {
// transform(root, currentNode.get(i), currentNode, Integer.toString(i));
// }
// }
//
// private void transformValueNodeBasedOnParent(JsonNode root, JsonNode currentNode, JsonNode parentNode, String fieldOrIndexInParent) {
// switch (parentNode.getNodeType()) {
// case OBJECT: ((ObjectNode)parentNode).set(fieldOrIndexInParent, transformValueNode(root, currentNode)); break;
// case ARRAY: ((ArrayNode)parentNode).set(Integer.valueOf(fieldOrIndexInParent), transformValueNode(root, currentNode)); break;
// default: break;
// }
// }
//
// abstract protected JsonNode transformValueNode(JsonNode root, JsonNode currentNode);
//
// }
//
// Path: yacl4j-core/src/main/java/com/yacl4j/core/PlaceholderResolver.java
// public interface PlaceholderResolver {
//
// void resolvePlaceholders(JsonNode configuration);
//
// }
//
// Path: yacl4j-core/src/main/java/com/yacl4j/core/util/JsonPointerUtils.java
// public class JsonPointerUtils {
//
// private JsonPointerUtils() { }
//
// private static final JsonPointer EMPTY_JSON_POINTER = JsonPointer.compile("");
//
// public static JsonPointer fromProperty(String property) {
// if (property.startsWith("/") || property.isEmpty()) {
// return JsonPointer.compile(property);
// } else {
// return JsonPointer.compile("/" + property);
// }
// }
//
// public static List<JsonPointer> heads(JsonPointer jsonPointer) {
// LinkedList<JsonPointer> heads = new LinkedList<>();
// while (!jsonPointer.equals(EMPTY_JSON_POINTER)) {
// jsonPointer = jsonPointer.head();
// heads.addFirst(jsonPointer);
// }
// return heads;
// }
//
// }
// Path: yacl4j-core/src/main/java/com/yacl4j/core/placeholder/NonRecursivePlaceholderResolver.java
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.yacl4j.core.AbstractNodeTransformer;
import com.yacl4j.core.PlaceholderResolver;
import com.yacl4j.core.util.JsonPointerUtils;
import yacl4j.repackaged.com.fasterxml.jackson.core.JsonPointer;
import yacl4j.repackaged.com.fasterxml.jackson.databind.JsonNode;
import yacl4j.repackaged.com.fasterxml.jackson.databind.node.TextNode;
} else {
return replacementNode;
}
}
private JsonNode resolveValueNodeByDereferencingValueNodes(JsonNode root, JsonNode currentNode, List<JsonPointerPlaceholder> matches) {
String resolvedValue = currentNode.asText();
for (JsonPointerPlaceholder match : matches) {
JsonNode replacementNode = root.at(match.jsonPointer);
if (!replacementNode.isMissingNode() && !replacementNode.isContainerNode()) {
resolvedValue = resolvedValue.replaceAll(Pattern.quote(match.placeholder), Matcher.quoteReplacement(replacementNode.asText()));
}
}
return TextNode.valueOf(resolvedValue);
}
private static class JsonPointerPlaceholder {
private String placeholder;
private JsonPointer jsonPointer;
private JsonPointerPlaceholder(String placeholder, JsonPointer jsonPointer) {
this.placeholder = placeholder;
this.jsonPointer = jsonPointer;
}
private static Optional<JsonPointerPlaceholder> parseJsonPointerPlaceholder(Matcher matcher) {
if (matcher.groupCount() == 2) {
String placeholder = matcher.group(1);
String property = matcher.group(2); | JsonPointer jsonPointer = JsonPointerUtils.fromProperty(property); |
fabriziocucci/yacl4j | yacl4j-core/src/test/java/com/yacl4j/core/ConfigurationBuilderWithSingleSourceTest.java | // Path: yacl4j-core/src/test/java/com/yacl4j/test/TestUtils.java
// public class TestUtils {
//
// public static File createConfigurationFile(String configuration, String fileExtension) throws IOException {
// File configurationFile = File.createTempFile("application", fileExtension);
// try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(configurationFile))) {
// bufferedWriter.write(configuration);
// return configurationFile;
// }
// }
//
// }
//
// Path: yacl4j-core/src/main/java/com/yacl4j/core/source/optional/ConfigurationSourceNotAvailableException.java
// public class ConfigurationSourceNotAvailableException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ConfigurationSourceNotAvailableException() {
// super();
// }
//
// public ConfigurationSourceNotAvailableException(String message) {
// super(message);
// }
//
// public ConfigurationSourceNotAvailableException(Throwable cause) {
// super(cause);
// }
//
// public ConfigurationSourceNotAvailableException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ConfigurationSourceNotAvailableException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
//
// }
| import static com.yacl4j.test.TestUtils.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.yacl4j.core.source.optional.ConfigurationSourceNotAvailableException;
import mockit.Mock;
import mockit.MockUp;
import mockit.integration.junit4.JMockit;
import yacl4j.repackaged.com.fasterxml.jackson.databind.JsonNode; | package com.yacl4j.core;
@RunWith(JMockit.class)
public class ConfigurationBuilderWithSingleSourceTest {
//////////
// file //
//////////
| // Path: yacl4j-core/src/test/java/com/yacl4j/test/TestUtils.java
// public class TestUtils {
//
// public static File createConfigurationFile(String configuration, String fileExtension) throws IOException {
// File configurationFile = File.createTempFile("application", fileExtension);
// try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(configurationFile))) {
// bufferedWriter.write(configuration);
// return configurationFile;
// }
// }
//
// }
//
// Path: yacl4j-core/src/main/java/com/yacl4j/core/source/optional/ConfigurationSourceNotAvailableException.java
// public class ConfigurationSourceNotAvailableException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ConfigurationSourceNotAvailableException() {
// super();
// }
//
// public ConfigurationSourceNotAvailableException(String message) {
// super(message);
// }
//
// public ConfigurationSourceNotAvailableException(Throwable cause) {
// super(cause);
// }
//
// public ConfigurationSourceNotAvailableException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ConfigurationSourceNotAvailableException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
//
// }
// Path: yacl4j-core/src/test/java/com/yacl4j/core/ConfigurationBuilderWithSingleSourceTest.java
import static com.yacl4j.test.TestUtils.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.yacl4j.core.source.optional.ConfigurationSourceNotAvailableException;
import mockit.Mock;
import mockit.MockUp;
import mockit.integration.junit4.JMockit;
import yacl4j.repackaged.com.fasterxml.jackson.databind.JsonNode;
package com.yacl4j.core;
@RunWith(JMockit.class)
public class ConfigurationBuilderWithSingleSourceTest {
//////////
// file //
//////////
| @Test(expected=ConfigurationSourceNotAvailableException.class) |
fabriziocucci/yacl4j | yacl4j-core/src/main/java/com/yacl4j/core/source/optional/OptionalConfigurationSourceBuilder.java | // Path: yacl4j-core/src/main/java/com/yacl4j/core/ConfigurationBuilder.java
// public class ConfigurationBuilder {
//
// private final List<ConfigurationSource> configurationSources;
// private PlaceholderResolver placeholderResolver;
// private Optional<ValueDecoder> valueDecoder;
//
// private ConfigurationBuilder() {
// this.configurationSources = new LinkedList<>();
// this.placeholderResolver = new NonRecursivePlaceholderResolver();
// this.valueDecoder = Optional.empty();
// }
//
// public static ConfigurationBuilder newBuilder() {
// return new ConfigurationBuilder();
// }
//
// public ConfigurationBuilder placeholderResolver(PlaceholderResolver placeholderResolver) {
// this.placeholderResolver = placeholderResolver;
// return this;
// }
//
// public ConfigurationBuilder valueDecoder(ValueDecoder valueDecoder) {
// this.valueDecoder = Optional.of(valueDecoder);
// return this;
// }
//
// public ConfigurationSourceBuilder source() {
// return new ConfigurationSourceBuilder(this);
// }
//
// public ConfigurationBuilder source(ConfigurationSource configurationSource) {
// this.configurationSources.add(configurationSource);
// return this;
// }
//
// public OptionalConfigurationSourceBuilder optionalSource() {
// return new OptionalConfigurationSourceBuilder(this);
// }
//
// public ConfigurationBuilder optionalSource(ConfigurationSource configurationSource) {
// return source(OptionalConfigurationSource.build(configurationSource));
// }
//
// public ConfigurationBuilder optionalSource(Supplier<ConfigurationSource> configurationSourceFactory) {
// return source(OptionalConfigurationSource.build(configurationSourceFactory));
// }
//
// public <T> T build(Class<T> configurationClass) {
// JsonNode configuration = mergeConfigurationSources();
// this.placeholderResolver.resolvePlaceholders(configuration);
// this.valueDecoder.ifPresent(valueDecoder -> valueDecoder.decodeValues(configuration));
// return ConfigurationUtils.toValue(configuration, configurationClass);
// }
//
// private JsonNode mergeConfigurationSources() {
// return configurationSources.stream()
// .map(ConfigurationSource::getConfiguration)
// .reduce(ConfigurationUtils.emptyConfiguration(), ConfigurationUtils::merge);
// }
//
// }
//
// Path: yacl4j-core/src/main/java/com/yacl4j/core/source/FileConfigurationSource.java
// public class FileConfigurationSource implements ConfigurationSource {
//
// private final InputStream configurationInputStream;
// private final Function<InputStream, JsonNode> configurationInputStreamReader;
//
// private FileConfigurationSource(InputStream configurationInputStream, Function<InputStream, JsonNode> configurationInputStreamReader) {
// this.configurationInputStream = configurationInputStream;
// this.configurationInputStreamReader = configurationInputStreamReader;
// }
//
// @Override
// public JsonNode getConfiguration() {
// return configurationInputStreamReader.apply(configurationInputStream);
// }
//
// public static FileConfigurationSource fromFileOnClasspath(String filename) {
// InputStream configurationInputStream = FileConfigurationSource.class.getClassLoader().getResourceAsStream(filename);
// if (configurationInputStream != null) {
// return selectFileConfigurationSource(filename, configurationInputStream);
// } else {
// throw new ConfigurationSourceNotAvailableException("Unable to find file on classpath: " + filename);
// }
// }
//
// public static FileConfigurationSource fromFileOnPath(String filename) {
// try {
// FileInputStream fileInputStream = new FileInputStream(filename);
// return selectFileConfigurationSource(filename, fileInputStream);
// } catch (FileNotFoundException fileNotFoundException) {
// throw new ConfigurationSourceNotAvailableException("Unable to find file on path: " + filename);
// }
// }
//
// public static FileConfigurationSource fromFile(File file) {
// return FileConfigurationSource.fromFileOnPath(file.getAbsolutePath());
// }
//
// private static FileConfigurationSource selectFileConfigurationSource(String filename, InputStream configurationInputStream) {
// if (filename.endsWith(".properties")) {
// return new FileConfigurationSource(configurationInputStream, ConfigurationUtils.Properties::fromInputStream);
// } else if (filename.endsWith(".yaml")) {
// return new FileConfigurationSource(configurationInputStream, ConfigurationUtils.Yaml::fromInputStream);
// } else if (filename.endsWith(".json")) {
// return new FileConfigurationSource(configurationInputStream, ConfigurationUtils.Json::fromInputStream);
// } else {
// throw new IllegalStateException("Configuration format not supported: " + filename);
// }
// }
//
// }
| import java.io.File;
import com.yacl4j.core.ConfigurationBuilder;
import com.yacl4j.core.source.FileConfigurationSource; | package com.yacl4j.core.source.optional;
public class OptionalConfigurationSourceBuilder {
private final ConfigurationBuilder configurationBuilder;
public OptionalConfigurationSourceBuilder(ConfigurationBuilder configurationBuilder) {
this.configurationBuilder = configurationBuilder;
}
public ConfigurationBuilder fromFile(File file) { | // Path: yacl4j-core/src/main/java/com/yacl4j/core/ConfigurationBuilder.java
// public class ConfigurationBuilder {
//
// private final List<ConfigurationSource> configurationSources;
// private PlaceholderResolver placeholderResolver;
// private Optional<ValueDecoder> valueDecoder;
//
// private ConfigurationBuilder() {
// this.configurationSources = new LinkedList<>();
// this.placeholderResolver = new NonRecursivePlaceholderResolver();
// this.valueDecoder = Optional.empty();
// }
//
// public static ConfigurationBuilder newBuilder() {
// return new ConfigurationBuilder();
// }
//
// public ConfigurationBuilder placeholderResolver(PlaceholderResolver placeholderResolver) {
// this.placeholderResolver = placeholderResolver;
// return this;
// }
//
// public ConfigurationBuilder valueDecoder(ValueDecoder valueDecoder) {
// this.valueDecoder = Optional.of(valueDecoder);
// return this;
// }
//
// public ConfigurationSourceBuilder source() {
// return new ConfigurationSourceBuilder(this);
// }
//
// public ConfigurationBuilder source(ConfigurationSource configurationSource) {
// this.configurationSources.add(configurationSource);
// return this;
// }
//
// public OptionalConfigurationSourceBuilder optionalSource() {
// return new OptionalConfigurationSourceBuilder(this);
// }
//
// public ConfigurationBuilder optionalSource(ConfigurationSource configurationSource) {
// return source(OptionalConfigurationSource.build(configurationSource));
// }
//
// public ConfigurationBuilder optionalSource(Supplier<ConfigurationSource> configurationSourceFactory) {
// return source(OptionalConfigurationSource.build(configurationSourceFactory));
// }
//
// public <T> T build(Class<T> configurationClass) {
// JsonNode configuration = mergeConfigurationSources();
// this.placeholderResolver.resolvePlaceholders(configuration);
// this.valueDecoder.ifPresent(valueDecoder -> valueDecoder.decodeValues(configuration));
// return ConfigurationUtils.toValue(configuration, configurationClass);
// }
//
// private JsonNode mergeConfigurationSources() {
// return configurationSources.stream()
// .map(ConfigurationSource::getConfiguration)
// .reduce(ConfigurationUtils.emptyConfiguration(), ConfigurationUtils::merge);
// }
//
// }
//
// Path: yacl4j-core/src/main/java/com/yacl4j/core/source/FileConfigurationSource.java
// public class FileConfigurationSource implements ConfigurationSource {
//
// private final InputStream configurationInputStream;
// private final Function<InputStream, JsonNode> configurationInputStreamReader;
//
// private FileConfigurationSource(InputStream configurationInputStream, Function<InputStream, JsonNode> configurationInputStreamReader) {
// this.configurationInputStream = configurationInputStream;
// this.configurationInputStreamReader = configurationInputStreamReader;
// }
//
// @Override
// public JsonNode getConfiguration() {
// return configurationInputStreamReader.apply(configurationInputStream);
// }
//
// public static FileConfigurationSource fromFileOnClasspath(String filename) {
// InputStream configurationInputStream = FileConfigurationSource.class.getClassLoader().getResourceAsStream(filename);
// if (configurationInputStream != null) {
// return selectFileConfigurationSource(filename, configurationInputStream);
// } else {
// throw new ConfigurationSourceNotAvailableException("Unable to find file on classpath: " + filename);
// }
// }
//
// public static FileConfigurationSource fromFileOnPath(String filename) {
// try {
// FileInputStream fileInputStream = new FileInputStream(filename);
// return selectFileConfigurationSource(filename, fileInputStream);
// } catch (FileNotFoundException fileNotFoundException) {
// throw new ConfigurationSourceNotAvailableException("Unable to find file on path: " + filename);
// }
// }
//
// public static FileConfigurationSource fromFile(File file) {
// return FileConfigurationSource.fromFileOnPath(file.getAbsolutePath());
// }
//
// private static FileConfigurationSource selectFileConfigurationSource(String filename, InputStream configurationInputStream) {
// if (filename.endsWith(".properties")) {
// return new FileConfigurationSource(configurationInputStream, ConfigurationUtils.Properties::fromInputStream);
// } else if (filename.endsWith(".yaml")) {
// return new FileConfigurationSource(configurationInputStream, ConfigurationUtils.Yaml::fromInputStream);
// } else if (filename.endsWith(".json")) {
// return new FileConfigurationSource(configurationInputStream, ConfigurationUtils.Json::fromInputStream);
// } else {
// throw new IllegalStateException("Configuration format not supported: " + filename);
// }
// }
//
// }
// Path: yacl4j-core/src/main/java/com/yacl4j/core/source/optional/OptionalConfigurationSourceBuilder.java
import java.io.File;
import com.yacl4j.core.ConfigurationBuilder;
import com.yacl4j.core.source.FileConfigurationSource;
package com.yacl4j.core.source.optional;
public class OptionalConfigurationSourceBuilder {
private final ConfigurationBuilder configurationBuilder;
public OptionalConfigurationSourceBuilder(ConfigurationBuilder configurationBuilder) {
this.configurationBuilder = configurationBuilder;
}
public ConfigurationBuilder fromFile(File file) { | return configurationBuilder.source(OptionalConfigurationSource.build(() -> FileConfigurationSource.fromFile(file))); |
dasmikko/facepunchdroid | app/src/main/java/com/apps/anker/facepunchdroid/Facepunch/Subscription.java | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Cookies/Cookies.java
// public class Cookies {
//
// public static String getCookie(String siteName,String CookieName){
// String CookieValue = null;
//
// CookieManager cookieManager = CookieManager.getInstance();
// String cookies = cookieManager.getCookie(siteName);
// String[] temp=cookies.split(";");
// for (String ar1 : temp ){
// if(ar1.contains(CookieName)){
// String[] temp1=ar1.split("=");
// CookieValue = temp1[1];
// }
// }
// return CookieValue;
// }
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Facepunch/Objects/SubscriptionFolder.java
// public class SubscriptionFolder {
// Integer id;
// String name;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
//
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import com.apps.anker.facepunchdroid.Cookies.Cookies;
import com.apps.anker.facepunchdroid.Facepunch.Objects.SubscriptionFolder;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList; | package com.apps.anker.facepunchdroid.Facepunch;
/**
* Created by Mikkel on 22-12-2016.
*/
public class Subscription {
//static ArrayList<SubscriptionFolder> subsarray = new ArrayList<>();
public static void createSubscription(Context context, final Integer threadID) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
final String securityToken = sharedPref.getString("securitytoken", null); | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Cookies/Cookies.java
// public class Cookies {
//
// public static String getCookie(String siteName,String CookieName){
// String CookieValue = null;
//
// CookieManager cookieManager = CookieManager.getInstance();
// String cookies = cookieManager.getCookie(siteName);
// String[] temp=cookies.split(";");
// for (String ar1 : temp ){
// if(ar1.contains(CookieName)){
// String[] temp1=ar1.split("=");
// CookieValue = temp1[1];
// }
// }
// return CookieValue;
// }
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Facepunch/Objects/SubscriptionFolder.java
// public class SubscriptionFolder {
// Integer id;
// String name;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
//
// }
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Facepunch/Subscription.java
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import com.apps.anker.facepunchdroid.Cookies.Cookies;
import com.apps.anker.facepunchdroid.Facepunch.Objects.SubscriptionFolder;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
package com.apps.anker.facepunchdroid.Facepunch;
/**
* Created by Mikkel on 22-12-2016.
*/
public class Subscription {
//static ArrayList<SubscriptionFolder> subsarray = new ArrayList<>();
public static void createSubscription(Context context, final Integer threadID) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
final String securityToken = sharedPref.getString("securitytoken", null); | final String bb_sessionhash = Cookies.getCookie("https://facepunch.com/", "bb_sessionhash"); |
dasmikko/facepunchdroid | app/src/main/java/com/apps/anker/facepunchdroid/Facepunch/Subscription.java | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Cookies/Cookies.java
// public class Cookies {
//
// public static String getCookie(String siteName,String CookieName){
// String CookieValue = null;
//
// CookieManager cookieManager = CookieManager.getInstance();
// String cookies = cookieManager.getCookie(siteName);
// String[] temp=cookies.split(";");
// for (String ar1 : temp ){
// if(ar1.contains(CookieName)){
// String[] temp1=ar1.split("=");
// CookieValue = temp1[1];
// }
// }
// return CookieValue;
// }
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Facepunch/Objects/SubscriptionFolder.java
// public class SubscriptionFolder {
// Integer id;
// String name;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
//
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import com.apps.anker.facepunchdroid.Cookies.Cookies;
import com.apps.anker.facepunchdroid.Facepunch.Objects.SubscriptionFolder;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList; | });
t.start();
}
public static void removeSubscription(final Integer threadID) {
final String bb_sessionhash = Cookies.getCookie("https://facepunch.com/", "bb_sessionhash");
final String bb_password = Cookies.getCookie("https://facepunch.com/", "bb_password");
final String bb_userid = Cookies.getCookie("https://facepunch.com/", "bb_userid");
Log.d("Notify", "Unsubscribing thread "+ threadID);
Thread t = new Thread(new Runnable() {
public void run() {
try {
Document doc = Jsoup.connect("https://facepunch.com/subscription.php?do=removesubscription&return=ucp&t="+threadID)
.cookie("bb_sessionhash", bb_sessionhash)
.cookie("bb_password", bb_password)
.cookie("bb_userid", bb_userid)
.get();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
| // Path: app/src/main/java/com/apps/anker/facepunchdroid/Cookies/Cookies.java
// public class Cookies {
//
// public static String getCookie(String siteName,String CookieName){
// String CookieValue = null;
//
// CookieManager cookieManager = CookieManager.getInstance();
// String cookies = cookieManager.getCookie(siteName);
// String[] temp=cookies.split(";");
// for (String ar1 : temp ){
// if(ar1.contains(CookieName)){
// String[] temp1=ar1.split("=");
// CookieValue = temp1[1];
// }
// }
// return CookieValue;
// }
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Facepunch/Objects/SubscriptionFolder.java
// public class SubscriptionFolder {
// Integer id;
// String name;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
//
// }
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Facepunch/Subscription.java
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import com.apps.anker.facepunchdroid.Cookies.Cookies;
import com.apps.anker.facepunchdroid.Facepunch.Objects.SubscriptionFolder;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
});
t.start();
}
public static void removeSubscription(final Integer threadID) {
final String bb_sessionhash = Cookies.getCookie("https://facepunch.com/", "bb_sessionhash");
final String bb_password = Cookies.getCookie("https://facepunch.com/", "bb_password");
final String bb_userid = Cookies.getCookie("https://facepunch.com/", "bb_userid");
Log.d("Notify", "Unsubscribing thread "+ threadID);
Thread t = new Thread(new Runnable() {
public void run() {
try {
Document doc = Jsoup.connect("https://facepunch.com/subscription.php?do=removesubscription&return=ucp&t="+threadID)
.cookie("bb_sessionhash", bb_sessionhash)
.cookie("bb_password", bb_password)
.cookie("bb_userid", bb_userid)
.get();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
| public static ArrayList<SubscriptionFolder> getSubscriptionFolders() throws IOException { |
dasmikko/facepunchdroid | app/src/main/java/com/apps/anker/facepunchdroid/Services/SubscribedThreadsReciever.java | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Cookies/Cookies.java
// public class Cookies {
//
// public static String getCookie(String siteName,String CookieName){
// String CookieValue = null;
//
// CookieManager cookieManager = CookieManager.getInstance();
// String cookies = cookieManager.getCookie(siteName);
// String[] temp=cookies.split(";");
// for (String ar1 : temp ){
// if(ar1.contains(CookieName)){
// String[] temp1=ar1.split("=");
// CookieValue = temp1[1];
// }
// }
// return CookieValue;
// }
// }
| import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import com.apps.anker.facepunchdroid.Cookies.Cookies;
import com.koushikdutta.ion.Ion;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static android.content.Context.NOTIFICATION_SERVICE; | package com.apps.anker.facepunchdroid.Services;
/**
* Created by Mikkel on 21-12-2016.
*/
public class SubscribedThreadsReciever extends BroadcastReceiver {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
Intent SubThreadsService;
Integer subthreadid;
Boolean wasSuccessful = false;
private NotificationManager mNM;
@Override
public void onReceive(final Context context, Intent intent) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
Log.d("Reciver", "On Recieve");
Log.d("Reciver", intent.getExtras().toString());
mNM = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
if(intent.getAction() != null) {
Log.d("getAction", intent.getAction());
if (intent.getAction().equals("removeSubThread")) {
Log.d("SubThreadNotifyList", "Removed thread from list");
//SubscribedThreadsService.notifiedThreads.remove(intent.getIntExtra("subthreadindex", 0));
}
if (intent.getAction().equals("checkForNewPosts")) {
ServiceManager serviceManager = new ServiceManager();
serviceManager.startSubscribedThreadsService(context);
}
if (intent.getAction().equals("unsubscribe")) {
subthreadid = intent.getExtras().getInt("viewThreadId"); | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Cookies/Cookies.java
// public class Cookies {
//
// public static String getCookie(String siteName,String CookieName){
// String CookieValue = null;
//
// CookieManager cookieManager = CookieManager.getInstance();
// String cookies = cookieManager.getCookie(siteName);
// String[] temp=cookies.split(";");
// for (String ar1 : temp ){
// if(ar1.contains(CookieName)){
// String[] temp1=ar1.split("=");
// CookieValue = temp1[1];
// }
// }
// return CookieValue;
// }
// }
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Services/SubscribedThreadsReciever.java
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import com.apps.anker.facepunchdroid.Cookies.Cookies;
import com.koushikdutta.ion.Ion;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static android.content.Context.NOTIFICATION_SERVICE;
package com.apps.anker.facepunchdroid.Services;
/**
* Created by Mikkel on 21-12-2016.
*/
public class SubscribedThreadsReciever extends BroadcastReceiver {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
Intent SubThreadsService;
Integer subthreadid;
Boolean wasSuccessful = false;
private NotificationManager mNM;
@Override
public void onReceive(final Context context, Intent intent) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
Log.d("Reciver", "On Recieve");
Log.d("Reciver", intent.getExtras().toString());
mNM = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
if(intent.getAction() != null) {
Log.d("getAction", intent.getAction());
if (intent.getAction().equals("removeSubThread")) {
Log.d("SubThreadNotifyList", "Removed thread from list");
//SubscribedThreadsService.notifiedThreads.remove(intent.getIntExtra("subthreadindex", 0));
}
if (intent.getAction().equals("checkForNewPosts")) {
ServiceManager serviceManager = new ServiceManager();
serviceManager.startSubscribedThreadsService(context);
}
if (intent.getAction().equals("unsubscribe")) {
subthreadid = intent.getExtras().getInt("viewThreadId"); | final String bb_sessionhash = Cookies.getCookie("https://facepunch.com/", "bb_sessionhash"); |
dasmikko/facepunchdroid | app/src/main/java/com/apps/anker/facepunchdroid/Tools/Downloading.java | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Constants.java
// public class Constants {
// public static final int schemaVersion = 2;
//
// public static final int DOWNLOAD_VIDEO_PERMISSION = 1000;
// public static final int DOWNLOAD_IMAGE_PERMISSION = 100;
// public static final int DOWNLOAD_URL_PERMISSION = 200;
//
// }
| import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import com.apps.anker.facepunchdroid.Constants; | package com.apps.anker.facepunchdroid.Tools;
/**
* Created by Mikkel on 20-05-2016.
*/
public class Downloading {
public static void downloadImage(Intent i, String url, Activity activity ) {
Intent intent = i;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
| // Path: app/src/main/java/com/apps/anker/facepunchdroid/Constants.java
// public class Constants {
// public static final int schemaVersion = 2;
//
// public static final int DOWNLOAD_VIDEO_PERMISSION = 1000;
// public static final int DOWNLOAD_IMAGE_PERMISSION = 100;
// public static final int DOWNLOAD_URL_PERMISSION = 200;
//
// }
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Tools/Downloading.java
import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import com.apps.anker.facepunchdroid.Constants;
package com.apps.anker.facepunchdroid.Tools;
/**
* Created by Mikkel on 20-05-2016.
*/
public class Downloading {
public static void downloadImage(Intent i, String url, Activity activity ) {
Intent intent = i;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
| activity.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constants.DOWNLOAD_IMAGE_PERMISSION); |
dasmikko/facepunchdroid | app/src/main/java/com/apps/anker/facepunchdroid/EditPinnedItemsActivity.java | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Adapters/PinnedItemsAdapter.java
// public class PinnedItemsAdapter extends ArrayAdapter<PinnedItem> {
//
// private List<PinnedItem> pinnedItems;
//
// public PinnedItemsAdapter(Context context, int resource, List<PinnedItem> objects) {
// super(context, resource, objects);
// pinnedItems = objects;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
//
// int dbPosition = position + 1;
//
// if(convertView == null) {
// convertView = LayoutInflater.from(getContext()).inflate(R.layout.pinneditem_list_item, parent, false);
// }
//
// Log.d("Position:", Integer.toString(position));
// PinnedItem pitem = pinnedItems.get(position);
//
// convertView.setTag(position);
// TextView titleText = (TextView) convertView.findViewById(R.id.item_title);
// titleText.setText(pitem.getTitle());
//
// return convertView;
// }
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Migrations/MainMigration.java
// public class MainMigration {
// // Example migration adding a new class
// static RealmMigration migration = new RealmMigration() {
// @Override
// public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
//
// // DynamicRealm exposes an editable schema
// RealmSchema schema = realm.getSchema();
//
// // Migrate to version 1: Add a new class.
// // Example:
// // public Person extends RealmObject {
// // private String name;
// // private int age;
// // // getters and setters left out for brevity
// // }
// if (oldVersion == 0) {
// schema.create("UserScript")
// .addField("title", String.class)
// .addField("url", String.class);
// oldVersion++;
// }
//
// if (oldVersion == 1) {
// schema.get("UserScript")
// .addField("javascript", String.class);
// oldVersion++;
// }
// }
// };
//
// public static RealmMigration getMigration() {
// return migration;
// }
//
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Tools/ShortcutsManager.java
// public class ShortcutsManager {
// public static void updateShortcuts(Realm realm, Activity activity) {
// /**
// * Shortcuts!
// */
// if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
// ShortcutManager shortcutManager = activity.getSystemService(ShortcutManager.class);
//
// ArrayList<ShortcutInfo> shortcutlist = new ArrayList<>();
//
// // Get Pinned items
// RealmResults<PinnedItem> pinnedItems = realm.where(PinnedItem.class).findAll();
//
// if (pinnedItems.size() > 0) {
// int count = 0;
// for (PinnedItem pitem : pinnedItems) {
// Intent linkIntent = new Intent(
// Intent.ACTION_VIEW,
// Uri.parse(pitem.getUrl()),
// activity,
// activity.getClass());
//
// linkIntent.putExtra("shortcut", pitem.getUrl());
//
//
// ShortcutInfo shortcut = new ShortcutInfo.Builder(activity, "shortcut" + count)
// .setShortLabel(pitem.getTitle())
// .setLongLabel(pitem.getTitle())
// .setIcon(Icon.createWithResource(activity, R.drawable.ic_link_black_24dp))
// .setIntent(linkIntent)
// .build();
//
// shortcutlist.add(shortcut);
// count++;
// }
//
// shortcutManager.setDynamicShortcuts(shortcutlist);
// }
// }
// }
// }
| import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.apps.anker.facepunchdroid.Adapters.PinnedItemsAdapter;
import com.apps.anker.facepunchdroid.Migrations.MainMigration;
import com.apps.anker.facepunchdroid.Tools.ShortcutsManager;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults; | package com.apps.anker.facepunchdroid;
public class EditPinnedItemsActivity extends AppCompatActivity {
PinnedItemsAdapter adapter;
ListView lv;
RealmResults<PinnedItem> pinnedItems;
// Pinned items
RealmConfiguration realmConfig;
Realm realm;
Activity mActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Realm.init(this);
setContentView(R.layout.activity_edit_pinned_items_activity);
mActivity = this;
// Create the Realm configuration
realmConfig = new RealmConfiguration.Builder()
.schemaVersion(Constants.schemaVersion) // Must be bumped when the schema changes | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Adapters/PinnedItemsAdapter.java
// public class PinnedItemsAdapter extends ArrayAdapter<PinnedItem> {
//
// private List<PinnedItem> pinnedItems;
//
// public PinnedItemsAdapter(Context context, int resource, List<PinnedItem> objects) {
// super(context, resource, objects);
// pinnedItems = objects;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
//
// int dbPosition = position + 1;
//
// if(convertView == null) {
// convertView = LayoutInflater.from(getContext()).inflate(R.layout.pinneditem_list_item, parent, false);
// }
//
// Log.d("Position:", Integer.toString(position));
// PinnedItem pitem = pinnedItems.get(position);
//
// convertView.setTag(position);
// TextView titleText = (TextView) convertView.findViewById(R.id.item_title);
// titleText.setText(pitem.getTitle());
//
// return convertView;
// }
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Migrations/MainMigration.java
// public class MainMigration {
// // Example migration adding a new class
// static RealmMigration migration = new RealmMigration() {
// @Override
// public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
//
// // DynamicRealm exposes an editable schema
// RealmSchema schema = realm.getSchema();
//
// // Migrate to version 1: Add a new class.
// // Example:
// // public Person extends RealmObject {
// // private String name;
// // private int age;
// // // getters and setters left out for brevity
// // }
// if (oldVersion == 0) {
// schema.create("UserScript")
// .addField("title", String.class)
// .addField("url", String.class);
// oldVersion++;
// }
//
// if (oldVersion == 1) {
// schema.get("UserScript")
// .addField("javascript", String.class);
// oldVersion++;
// }
// }
// };
//
// public static RealmMigration getMigration() {
// return migration;
// }
//
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Tools/ShortcutsManager.java
// public class ShortcutsManager {
// public static void updateShortcuts(Realm realm, Activity activity) {
// /**
// * Shortcuts!
// */
// if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
// ShortcutManager shortcutManager = activity.getSystemService(ShortcutManager.class);
//
// ArrayList<ShortcutInfo> shortcutlist = new ArrayList<>();
//
// // Get Pinned items
// RealmResults<PinnedItem> pinnedItems = realm.where(PinnedItem.class).findAll();
//
// if (pinnedItems.size() > 0) {
// int count = 0;
// for (PinnedItem pitem : pinnedItems) {
// Intent linkIntent = new Intent(
// Intent.ACTION_VIEW,
// Uri.parse(pitem.getUrl()),
// activity,
// activity.getClass());
//
// linkIntent.putExtra("shortcut", pitem.getUrl());
//
//
// ShortcutInfo shortcut = new ShortcutInfo.Builder(activity, "shortcut" + count)
// .setShortLabel(pitem.getTitle())
// .setLongLabel(pitem.getTitle())
// .setIcon(Icon.createWithResource(activity, R.drawable.ic_link_black_24dp))
// .setIntent(linkIntent)
// .build();
//
// shortcutlist.add(shortcut);
// count++;
// }
//
// shortcutManager.setDynamicShortcuts(shortcutlist);
// }
// }
// }
// }
// Path: app/src/main/java/com/apps/anker/facepunchdroid/EditPinnedItemsActivity.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.apps.anker.facepunchdroid.Adapters.PinnedItemsAdapter;
import com.apps.anker.facepunchdroid.Migrations.MainMigration;
import com.apps.anker.facepunchdroid.Tools.ShortcutsManager;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;
package com.apps.anker.facepunchdroid;
public class EditPinnedItemsActivity extends AppCompatActivity {
PinnedItemsAdapter adapter;
ListView lv;
RealmResults<PinnedItem> pinnedItems;
// Pinned items
RealmConfiguration realmConfig;
Realm realm;
Activity mActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Realm.init(this);
setContentView(R.layout.activity_edit_pinned_items_activity);
mActivity = this;
// Create the Realm configuration
realmConfig = new RealmConfiguration.Builder()
.schemaVersion(Constants.schemaVersion) // Must be bumped when the schema changes | .migration(MainMigration.getMigration()) // Migration to run instead of throwing an exception |
dasmikko/facepunchdroid | app/src/main/java/com/apps/anker/facepunchdroid/EditPinnedItemsActivity.java | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Adapters/PinnedItemsAdapter.java
// public class PinnedItemsAdapter extends ArrayAdapter<PinnedItem> {
//
// private List<PinnedItem> pinnedItems;
//
// public PinnedItemsAdapter(Context context, int resource, List<PinnedItem> objects) {
// super(context, resource, objects);
// pinnedItems = objects;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
//
// int dbPosition = position + 1;
//
// if(convertView == null) {
// convertView = LayoutInflater.from(getContext()).inflate(R.layout.pinneditem_list_item, parent, false);
// }
//
// Log.d("Position:", Integer.toString(position));
// PinnedItem pitem = pinnedItems.get(position);
//
// convertView.setTag(position);
// TextView titleText = (TextView) convertView.findViewById(R.id.item_title);
// titleText.setText(pitem.getTitle());
//
// return convertView;
// }
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Migrations/MainMigration.java
// public class MainMigration {
// // Example migration adding a new class
// static RealmMigration migration = new RealmMigration() {
// @Override
// public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
//
// // DynamicRealm exposes an editable schema
// RealmSchema schema = realm.getSchema();
//
// // Migrate to version 1: Add a new class.
// // Example:
// // public Person extends RealmObject {
// // private String name;
// // private int age;
// // // getters and setters left out for brevity
// // }
// if (oldVersion == 0) {
// schema.create("UserScript")
// .addField("title", String.class)
// .addField("url", String.class);
// oldVersion++;
// }
//
// if (oldVersion == 1) {
// schema.get("UserScript")
// .addField("javascript", String.class);
// oldVersion++;
// }
// }
// };
//
// public static RealmMigration getMigration() {
// return migration;
// }
//
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Tools/ShortcutsManager.java
// public class ShortcutsManager {
// public static void updateShortcuts(Realm realm, Activity activity) {
// /**
// * Shortcuts!
// */
// if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
// ShortcutManager shortcutManager = activity.getSystemService(ShortcutManager.class);
//
// ArrayList<ShortcutInfo> shortcutlist = new ArrayList<>();
//
// // Get Pinned items
// RealmResults<PinnedItem> pinnedItems = realm.where(PinnedItem.class).findAll();
//
// if (pinnedItems.size() > 0) {
// int count = 0;
// for (PinnedItem pitem : pinnedItems) {
// Intent linkIntent = new Intent(
// Intent.ACTION_VIEW,
// Uri.parse(pitem.getUrl()),
// activity,
// activity.getClass());
//
// linkIntent.putExtra("shortcut", pitem.getUrl());
//
//
// ShortcutInfo shortcut = new ShortcutInfo.Builder(activity, "shortcut" + count)
// .setShortLabel(pitem.getTitle())
// .setLongLabel(pitem.getTitle())
// .setIcon(Icon.createWithResource(activity, R.drawable.ic_link_black_24dp))
// .setIntent(linkIntent)
// .build();
//
// shortcutlist.add(shortcut);
// count++;
// }
//
// shortcutManager.setDynamicShortcuts(shortcutlist);
// }
// }
// }
// }
| import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.apps.anker.facepunchdroid.Adapters.PinnedItemsAdapter;
import com.apps.anker.facepunchdroid.Migrations.MainMigration;
import com.apps.anker.facepunchdroid.Tools.ShortcutsManager;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults; |
adapter.notifyDataSetChanged();
updateShortcuts();
break;
}
}
});
builder.create().show();
/*PinnedItem item = pinnedItems.get(Integer.parseInt(view.getTag().toString()));
//Toast.makeText(getApplicationContext() ,item.getTitle() + " deleted",Toast.LENGTH_SHORT).show();
Snackbar.make(mlayout,"Item: " + item.getTitle() + " was deleted", Snackbar.LENGTH_LONG).show();
// Remove from Realm
realm.beginTransaction();
pinnedItems.remove(position);
realm.commitTransaction();*/
}
});
}
}
private void updateShortcuts() { | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Adapters/PinnedItemsAdapter.java
// public class PinnedItemsAdapter extends ArrayAdapter<PinnedItem> {
//
// private List<PinnedItem> pinnedItems;
//
// public PinnedItemsAdapter(Context context, int resource, List<PinnedItem> objects) {
// super(context, resource, objects);
// pinnedItems = objects;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
//
// int dbPosition = position + 1;
//
// if(convertView == null) {
// convertView = LayoutInflater.from(getContext()).inflate(R.layout.pinneditem_list_item, parent, false);
// }
//
// Log.d("Position:", Integer.toString(position));
// PinnedItem pitem = pinnedItems.get(position);
//
// convertView.setTag(position);
// TextView titleText = (TextView) convertView.findViewById(R.id.item_title);
// titleText.setText(pitem.getTitle());
//
// return convertView;
// }
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Migrations/MainMigration.java
// public class MainMigration {
// // Example migration adding a new class
// static RealmMigration migration = new RealmMigration() {
// @Override
// public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
//
// // DynamicRealm exposes an editable schema
// RealmSchema schema = realm.getSchema();
//
// // Migrate to version 1: Add a new class.
// // Example:
// // public Person extends RealmObject {
// // private String name;
// // private int age;
// // // getters and setters left out for brevity
// // }
// if (oldVersion == 0) {
// schema.create("UserScript")
// .addField("title", String.class)
// .addField("url", String.class);
// oldVersion++;
// }
//
// if (oldVersion == 1) {
// schema.get("UserScript")
// .addField("javascript", String.class);
// oldVersion++;
// }
// }
// };
//
// public static RealmMigration getMigration() {
// return migration;
// }
//
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Tools/ShortcutsManager.java
// public class ShortcutsManager {
// public static void updateShortcuts(Realm realm, Activity activity) {
// /**
// * Shortcuts!
// */
// if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
// ShortcutManager shortcutManager = activity.getSystemService(ShortcutManager.class);
//
// ArrayList<ShortcutInfo> shortcutlist = new ArrayList<>();
//
// // Get Pinned items
// RealmResults<PinnedItem> pinnedItems = realm.where(PinnedItem.class).findAll();
//
// if (pinnedItems.size() > 0) {
// int count = 0;
// for (PinnedItem pitem : pinnedItems) {
// Intent linkIntent = new Intent(
// Intent.ACTION_VIEW,
// Uri.parse(pitem.getUrl()),
// activity,
// activity.getClass());
//
// linkIntent.putExtra("shortcut", pitem.getUrl());
//
//
// ShortcutInfo shortcut = new ShortcutInfo.Builder(activity, "shortcut" + count)
// .setShortLabel(pitem.getTitle())
// .setLongLabel(pitem.getTitle())
// .setIcon(Icon.createWithResource(activity, R.drawable.ic_link_black_24dp))
// .setIntent(linkIntent)
// .build();
//
// shortcutlist.add(shortcut);
// count++;
// }
//
// shortcutManager.setDynamicShortcuts(shortcutlist);
// }
// }
// }
// }
// Path: app/src/main/java/com/apps/anker/facepunchdroid/EditPinnedItemsActivity.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.apps.anker.facepunchdroid.Adapters.PinnedItemsAdapter;
import com.apps.anker.facepunchdroid.Migrations.MainMigration;
import com.apps.anker.facepunchdroid.Tools.ShortcutsManager;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;
adapter.notifyDataSetChanged();
updateShortcuts();
break;
}
}
});
builder.create().show();
/*PinnedItem item = pinnedItems.get(Integer.parseInt(view.getTag().toString()));
//Toast.makeText(getApplicationContext() ,item.getTitle() + " deleted",Toast.LENGTH_SHORT).show();
Snackbar.make(mlayout,"Item: " + item.getTitle() + " was deleted", Snackbar.LENGTH_LONG).show();
// Remove from Realm
realm.beginTransaction();
pinnedItems.remove(position);
realm.commitTransaction();*/
}
});
}
}
private void updateShortcuts() { | ShortcutsManager.updateShortcuts(realm, mActivity); |
dasmikko/facepunchdroid | app/src/main/java/com/apps/anker/facepunchdroid/ImageViewer.java | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Tools/Downloading.java
// public class Downloading {
//
//
// public static void downloadImage(Intent i, String url, Activity activity ) {
// Intent intent = i;
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.READ_EXTERNAL_STORAGE)
// != PackageManager.PERMISSION_GRANTED) {
//
// activity.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constants.DOWNLOAD_IMAGE_PERMISSION);
// return;
// }
// }
//
//
// DownloadManager downloadManager = (DownloadManager)activity.getSystemService(activity.DOWNLOAD_SERVICE);
// Uri Download_Uri = Uri.parse(url);
//
// DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//
// //Restrict the types of networks over which this download may proceed.
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//
// //Set whether this download may proceed over a roaming connection.
// request.setAllowedOverRoaming(false);
//
// //Set the title of this download, to be displayed in notifications.
// request.setTitle(url.substring(url.lastIndexOf('/') + 1));
//
// //Set the local destination for the downloaded file to a path within the application's external files directory
// request.setDestinationInExternalPublicDir("Facepunch Droid", url.substring(url.lastIndexOf('/') + 1));
//
// //Enqueue a new download and same the referenceId
// Long downloadReference = downloadManager.enqueue(request);
// }
//
// public static void downloadUrl(Intent i, String url, Activity activity ) {
// Intent intent = i;
// DownloadManager downloadManager = (DownloadManager)activity.getSystemService(activity.DOWNLOAD_SERVICE);
// Uri Download_Uri = Uri.parse(url);
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.READ_EXTERNAL_STORAGE)
// != PackageManager.PERMISSION_GRANTED) {
//
// activity.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constants.DOWNLOAD_URL_PERMISSION);
// return;
// }
// }
//
// DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//
// //Restrict the types of networks over which this download may proceed.
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//
// //Set whether this download may proceed over a roaming connection.
// request.setAllowedOverRoaming(false);
//
// //Set the title of this download, to be displayed in notifications.
// request.setTitle(url.substring(url.lastIndexOf('/') + 1));
//
// //Set the local destination for the downloaded file to a path within the application's external files directory
// // For download folder use: Environment.DIRECTORY_DOWNLOADS
//
// request.setDestinationInExternalPublicDir("Facepunch Droid", url.substring(url.lastIndexOf('/') + 1));
//
// //Enqueue a new download and same the referenceId
// Long downloadReference = downloadManager.enqueue(request);
// }
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Tools/Language.java
// public class Language {
// public static void setLanguage(String lang, Resources res) {
// Locale myLocale = null;
//
// Log.d("New Language",lang);
//
// if(lang.equals("system")) {
// myLocale = new Locale(Locale.getDefault().getLanguage());
// Log.d("System Language", Locale.getDefault().getLanguage());
// } else {
// myLocale = new Locale(lang.toString());
// }
//
// Locale.setDefault(myLocale);
// Configuration config = new Configuration();
// config.locale = myLocale;
// res.updateConfiguration(config, res.getDisplayMetrics());
//
// }
// }
| import android.Manifest;
import android.app.ActionBar;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.apps.anker.facepunchdroid.Tools.Downloading;
import com.apps.anker.facepunchdroid.Tools.Language;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.nbsp.materialfilepicker.MaterialFilePicker;
import java.util.regex.Pattern;
import uk.co.senab.photoview.PhotoViewAttacher; | package com.apps.anker.facepunchdroid;
public class ImageViewer extends AppCompatActivity {
PhotoViewAttacher mAttacher;
ImageView imgView;
String url;
String fileType;
private SharedPreferences sharedPref;
String selectedLang;
ProgressBar pb;
@Override
protected void onCreate(Bundle savedInstanceState) {
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// Update language
selectedLang = sharedPref.getString("language", "system"); | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Tools/Downloading.java
// public class Downloading {
//
//
// public static void downloadImage(Intent i, String url, Activity activity ) {
// Intent intent = i;
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.READ_EXTERNAL_STORAGE)
// != PackageManager.PERMISSION_GRANTED) {
//
// activity.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constants.DOWNLOAD_IMAGE_PERMISSION);
// return;
// }
// }
//
//
// DownloadManager downloadManager = (DownloadManager)activity.getSystemService(activity.DOWNLOAD_SERVICE);
// Uri Download_Uri = Uri.parse(url);
//
// DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//
// //Restrict the types of networks over which this download may proceed.
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//
// //Set whether this download may proceed over a roaming connection.
// request.setAllowedOverRoaming(false);
//
// //Set the title of this download, to be displayed in notifications.
// request.setTitle(url.substring(url.lastIndexOf('/') + 1));
//
// //Set the local destination for the downloaded file to a path within the application's external files directory
// request.setDestinationInExternalPublicDir("Facepunch Droid", url.substring(url.lastIndexOf('/') + 1));
//
// //Enqueue a new download and same the referenceId
// Long downloadReference = downloadManager.enqueue(request);
// }
//
// public static void downloadUrl(Intent i, String url, Activity activity ) {
// Intent intent = i;
// DownloadManager downloadManager = (DownloadManager)activity.getSystemService(activity.DOWNLOAD_SERVICE);
// Uri Download_Uri = Uri.parse(url);
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.READ_EXTERNAL_STORAGE)
// != PackageManager.PERMISSION_GRANTED) {
//
// activity.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constants.DOWNLOAD_URL_PERMISSION);
// return;
// }
// }
//
// DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//
// //Restrict the types of networks over which this download may proceed.
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//
// //Set whether this download may proceed over a roaming connection.
// request.setAllowedOverRoaming(false);
//
// //Set the title of this download, to be displayed in notifications.
// request.setTitle(url.substring(url.lastIndexOf('/') + 1));
//
// //Set the local destination for the downloaded file to a path within the application's external files directory
// // For download folder use: Environment.DIRECTORY_DOWNLOADS
//
// request.setDestinationInExternalPublicDir("Facepunch Droid", url.substring(url.lastIndexOf('/') + 1));
//
// //Enqueue a new download and same the referenceId
// Long downloadReference = downloadManager.enqueue(request);
// }
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Tools/Language.java
// public class Language {
// public static void setLanguage(String lang, Resources res) {
// Locale myLocale = null;
//
// Log.d("New Language",lang);
//
// if(lang.equals("system")) {
// myLocale = new Locale(Locale.getDefault().getLanguage());
// Log.d("System Language", Locale.getDefault().getLanguage());
// } else {
// myLocale = new Locale(lang.toString());
// }
//
// Locale.setDefault(myLocale);
// Configuration config = new Configuration();
// config.locale = myLocale;
// res.updateConfiguration(config, res.getDisplayMetrics());
//
// }
// }
// Path: app/src/main/java/com/apps/anker/facepunchdroid/ImageViewer.java
import android.Manifest;
import android.app.ActionBar;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.apps.anker.facepunchdroid.Tools.Downloading;
import com.apps.anker.facepunchdroid.Tools.Language;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.nbsp.materialfilepicker.MaterialFilePicker;
import java.util.regex.Pattern;
import uk.co.senab.photoview.PhotoViewAttacher;
package com.apps.anker.facepunchdroid;
public class ImageViewer extends AppCompatActivity {
PhotoViewAttacher mAttacher;
ImageView imgView;
String url;
String fileType;
private SharedPreferences sharedPref;
String selectedLang;
ProgressBar pb;
@Override
protected void onCreate(Bundle savedInstanceState) {
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// Update language
selectedLang = sharedPref.getString("language", "system"); | Language.setLanguage(selectedLang, getResources()); |
dasmikko/facepunchdroid | app/src/main/java/com/apps/anker/facepunchdroid/ImageViewer.java | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Tools/Downloading.java
// public class Downloading {
//
//
// public static void downloadImage(Intent i, String url, Activity activity ) {
// Intent intent = i;
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.READ_EXTERNAL_STORAGE)
// != PackageManager.PERMISSION_GRANTED) {
//
// activity.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constants.DOWNLOAD_IMAGE_PERMISSION);
// return;
// }
// }
//
//
// DownloadManager downloadManager = (DownloadManager)activity.getSystemService(activity.DOWNLOAD_SERVICE);
// Uri Download_Uri = Uri.parse(url);
//
// DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//
// //Restrict the types of networks over which this download may proceed.
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//
// //Set whether this download may proceed over a roaming connection.
// request.setAllowedOverRoaming(false);
//
// //Set the title of this download, to be displayed in notifications.
// request.setTitle(url.substring(url.lastIndexOf('/') + 1));
//
// //Set the local destination for the downloaded file to a path within the application's external files directory
// request.setDestinationInExternalPublicDir("Facepunch Droid", url.substring(url.lastIndexOf('/') + 1));
//
// //Enqueue a new download and same the referenceId
// Long downloadReference = downloadManager.enqueue(request);
// }
//
// public static void downloadUrl(Intent i, String url, Activity activity ) {
// Intent intent = i;
// DownloadManager downloadManager = (DownloadManager)activity.getSystemService(activity.DOWNLOAD_SERVICE);
// Uri Download_Uri = Uri.parse(url);
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.READ_EXTERNAL_STORAGE)
// != PackageManager.PERMISSION_GRANTED) {
//
// activity.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constants.DOWNLOAD_URL_PERMISSION);
// return;
// }
// }
//
// DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//
// //Restrict the types of networks over which this download may proceed.
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//
// //Set whether this download may proceed over a roaming connection.
// request.setAllowedOverRoaming(false);
//
// //Set the title of this download, to be displayed in notifications.
// request.setTitle(url.substring(url.lastIndexOf('/') + 1));
//
// //Set the local destination for the downloaded file to a path within the application's external files directory
// // For download folder use: Environment.DIRECTORY_DOWNLOADS
//
// request.setDestinationInExternalPublicDir("Facepunch Droid", url.substring(url.lastIndexOf('/') + 1));
//
// //Enqueue a new download and same the referenceId
// Long downloadReference = downloadManager.enqueue(request);
// }
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Tools/Language.java
// public class Language {
// public static void setLanguage(String lang, Resources res) {
// Locale myLocale = null;
//
// Log.d("New Language",lang);
//
// if(lang.equals("system")) {
// myLocale = new Locale(Locale.getDefault().getLanguage());
// Log.d("System Language", Locale.getDefault().getLanguage());
// } else {
// myLocale = new Locale(lang.toString());
// }
//
// Locale.setDefault(myLocale);
// Configuration config = new Configuration();
// config.locale = myLocale;
// res.updateConfiguration(config, res.getDisplayMetrics());
//
// }
// }
| import android.Manifest;
import android.app.ActionBar;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.apps.anker.facepunchdroid.Tools.Downloading;
import com.apps.anker.facepunchdroid.Tools.Language;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.nbsp.materialfilepicker.MaterialFilePicker;
import java.util.regex.Pattern;
import uk.co.senab.photoview.PhotoViewAttacher; |
@Override
public void onOutsidePhotoTap() {
finish();
}
}
public void onViewTap(View view, float x, float y) {
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_imageviewer_actionbar, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.action_download:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
} else { | // Path: app/src/main/java/com/apps/anker/facepunchdroid/Tools/Downloading.java
// public class Downloading {
//
//
// public static void downloadImage(Intent i, String url, Activity activity ) {
// Intent intent = i;
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.READ_EXTERNAL_STORAGE)
// != PackageManager.PERMISSION_GRANTED) {
//
// activity.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constants.DOWNLOAD_IMAGE_PERMISSION);
// return;
// }
// }
//
//
// DownloadManager downloadManager = (DownloadManager)activity.getSystemService(activity.DOWNLOAD_SERVICE);
// Uri Download_Uri = Uri.parse(url);
//
// DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//
// //Restrict the types of networks over which this download may proceed.
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//
// //Set whether this download may proceed over a roaming connection.
// request.setAllowedOverRoaming(false);
//
// //Set the title of this download, to be displayed in notifications.
// request.setTitle(url.substring(url.lastIndexOf('/') + 1));
//
// //Set the local destination for the downloaded file to a path within the application's external files directory
// request.setDestinationInExternalPublicDir("Facepunch Droid", url.substring(url.lastIndexOf('/') + 1));
//
// //Enqueue a new download and same the referenceId
// Long downloadReference = downloadManager.enqueue(request);
// }
//
// public static void downloadUrl(Intent i, String url, Activity activity ) {
// Intent intent = i;
// DownloadManager downloadManager = (DownloadManager)activity.getSystemService(activity.DOWNLOAD_SERVICE);
// Uri Download_Uri = Uri.parse(url);
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (ContextCompat.checkSelfPermission(activity,
// Manifest.permission.READ_EXTERNAL_STORAGE)
// != PackageManager.PERMISSION_GRANTED) {
//
// activity.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constants.DOWNLOAD_URL_PERMISSION);
// return;
// }
// }
//
// DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//
// //Restrict the types of networks over which this download may proceed.
// request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//
// //Set whether this download may proceed over a roaming connection.
// request.setAllowedOverRoaming(false);
//
// //Set the title of this download, to be displayed in notifications.
// request.setTitle(url.substring(url.lastIndexOf('/') + 1));
//
// //Set the local destination for the downloaded file to a path within the application's external files directory
// // For download folder use: Environment.DIRECTORY_DOWNLOADS
//
// request.setDestinationInExternalPublicDir("Facepunch Droid", url.substring(url.lastIndexOf('/') + 1));
//
// //Enqueue a new download and same the referenceId
// Long downloadReference = downloadManager.enqueue(request);
// }
// }
//
// Path: app/src/main/java/com/apps/anker/facepunchdroid/Tools/Language.java
// public class Language {
// public static void setLanguage(String lang, Resources res) {
// Locale myLocale = null;
//
// Log.d("New Language",lang);
//
// if(lang.equals("system")) {
// myLocale = new Locale(Locale.getDefault().getLanguage());
// Log.d("System Language", Locale.getDefault().getLanguage());
// } else {
// myLocale = new Locale(lang.toString());
// }
//
// Locale.setDefault(myLocale);
// Configuration config = new Configuration();
// config.locale = myLocale;
// res.updateConfiguration(config, res.getDisplayMetrics());
//
// }
// }
// Path: app/src/main/java/com/apps/anker/facepunchdroid/ImageViewer.java
import android.Manifest;
import android.app.ActionBar;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.apps.anker.facepunchdroid.Tools.Downloading;
import com.apps.anker.facepunchdroid.Tools.Language;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.nbsp.materialfilepicker.MaterialFilePicker;
import java.util.regex.Pattern;
import uk.co.senab.photoview.PhotoViewAttacher;
@Override
public void onOutsidePhotoTap() {
finish();
}
}
public void onViewTap(View view, float x, float y) {
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_imageviewer_actionbar, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.action_download:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
} else { | Downloading.downloadImage(getIntent(), Uri.parse(url).toString(), this); |
diffplug/durian | test/com/diffplug/common/base/ErrorsTest.java | // Path: src/com/diffplug/common/base/Errors.java
// public interface Dialog extends Consumer<Throwable> {}
//
// Path: src/com/diffplug/common/base/Errors.java
// public interface Log extends Consumer<Throwable> {}
| import org.junit.Assert;
import org.junit.Test;
import com.diffplug.common.base.Errors.Plugins.Dialog;
import com.diffplug.common.base.Errors.Plugins.Log; | System.clearProperty("durian.plugins.com.diffplug.common.base.Errors.Plugins.Suppress");
DurianPlugins.resetForTesting();
Errors.resetForTesting();
}
}
@Test
public void testWrapWithDefault() {
// function
Assert.assertEquals("called", Errors.suppress().wrapWithDefault(input -> "called", "default").apply(null));
Assert.assertEquals("default", Errors.suppress().wrapWithDefault(input -> {
throw new IllegalArgumentException();
}, "default").apply(null));
// supplier
Assert.assertEquals("called", Errors.suppress().wrapWithDefault(() -> "called", "default").get());
Assert.assertEquals("default", Errors.suppress().wrapWithDefault(() -> {
throw new IllegalArgumentException();
}, "default").get());
// predicate
Assert.assertEquals(true, Errors.suppress().wrapWithDefault(input -> true, false).test(null));
Assert.assertEquals(false, Errors.suppress().wrapWithDefault(input -> {
throw new IllegalArgumentException();
}, false).test(null));
}
@Test
public void testWiresCrossed() {
DurianPlugins.resetForTesting();
Errors.resetForTesting();
| // Path: src/com/diffplug/common/base/Errors.java
// public interface Dialog extends Consumer<Throwable> {}
//
// Path: src/com/diffplug/common/base/Errors.java
// public interface Log extends Consumer<Throwable> {}
// Path: test/com/diffplug/common/base/ErrorsTest.java
import org.junit.Assert;
import org.junit.Test;
import com.diffplug.common.base.Errors.Plugins.Dialog;
import com.diffplug.common.base.Errors.Plugins.Log;
System.clearProperty("durian.plugins.com.diffplug.common.base.Errors.Plugins.Suppress");
DurianPlugins.resetForTesting();
Errors.resetForTesting();
}
}
@Test
public void testWrapWithDefault() {
// function
Assert.assertEquals("called", Errors.suppress().wrapWithDefault(input -> "called", "default").apply(null));
Assert.assertEquals("default", Errors.suppress().wrapWithDefault(input -> {
throw new IllegalArgumentException();
}, "default").apply(null));
// supplier
Assert.assertEquals("called", Errors.suppress().wrapWithDefault(() -> "called", "default").get());
Assert.assertEquals("default", Errors.suppress().wrapWithDefault(() -> {
throw new IllegalArgumentException();
}, "default").get());
// predicate
Assert.assertEquals(true, Errors.suppress().wrapWithDefault(input -> true, false).test(null));
Assert.assertEquals(false, Errors.suppress().wrapWithDefault(input -> {
throw new IllegalArgumentException();
}, false).test(null));
}
@Test
public void testWiresCrossed() {
DurianPlugins.resetForTesting();
Errors.resetForTesting();
| DurianPlugins.register(Errors.Plugins.Log.class, new TestHandler("Log")); |
diffplug/durian | test/com/diffplug/common/base/ErrorsTest.java | // Path: src/com/diffplug/common/base/Errors.java
// public interface Dialog extends Consumer<Throwable> {}
//
// Path: src/com/diffplug/common/base/Errors.java
// public interface Log extends Consumer<Throwable> {}
| import org.junit.Assert;
import org.junit.Test;
import com.diffplug.common.base.Errors.Plugins.Dialog;
import com.diffplug.common.base.Errors.Plugins.Log; | DurianPlugins.resetForTesting();
Errors.resetForTesting();
}
}
@Test
public void testWrapWithDefault() {
// function
Assert.assertEquals("called", Errors.suppress().wrapWithDefault(input -> "called", "default").apply(null));
Assert.assertEquals("default", Errors.suppress().wrapWithDefault(input -> {
throw new IllegalArgumentException();
}, "default").apply(null));
// supplier
Assert.assertEquals("called", Errors.suppress().wrapWithDefault(() -> "called", "default").get());
Assert.assertEquals("default", Errors.suppress().wrapWithDefault(() -> {
throw new IllegalArgumentException();
}, "default").get());
// predicate
Assert.assertEquals(true, Errors.suppress().wrapWithDefault(input -> true, false).test(null));
Assert.assertEquals(false, Errors.suppress().wrapWithDefault(input -> {
throw new IllegalArgumentException();
}, false).test(null));
}
@Test
public void testWiresCrossed() {
DurianPlugins.resetForTesting();
Errors.resetForTesting();
DurianPlugins.register(Errors.Plugins.Log.class, new TestHandler("Log")); | // Path: src/com/diffplug/common/base/Errors.java
// public interface Dialog extends Consumer<Throwable> {}
//
// Path: src/com/diffplug/common/base/Errors.java
// public interface Log extends Consumer<Throwable> {}
// Path: test/com/diffplug/common/base/ErrorsTest.java
import org.junit.Assert;
import org.junit.Test;
import com.diffplug.common.base.Errors.Plugins.Dialog;
import com.diffplug.common.base.Errors.Plugins.Log;
DurianPlugins.resetForTesting();
Errors.resetForTesting();
}
}
@Test
public void testWrapWithDefault() {
// function
Assert.assertEquals("called", Errors.suppress().wrapWithDefault(input -> "called", "default").apply(null));
Assert.assertEquals("default", Errors.suppress().wrapWithDefault(input -> {
throw new IllegalArgumentException();
}, "default").apply(null));
// supplier
Assert.assertEquals("called", Errors.suppress().wrapWithDefault(() -> "called", "default").get());
Assert.assertEquals("default", Errors.suppress().wrapWithDefault(() -> {
throw new IllegalArgumentException();
}, "default").get());
// predicate
Assert.assertEquals(true, Errors.suppress().wrapWithDefault(input -> true, false).test(null));
Assert.assertEquals(false, Errors.suppress().wrapWithDefault(input -> {
throw new IllegalArgumentException();
}, false).test(null));
}
@Test
public void testWiresCrossed() {
DurianPlugins.resetForTesting();
Errors.resetForTesting();
DurianPlugins.register(Errors.Plugins.Log.class, new TestHandler("Log")); | DurianPlugins.register(Errors.Plugins.Dialog.class, new TestHandler("Dialog")); |
janoliver/pOT-Droid | src/main/java/com/mde/potdroid/helpers/BenderJSInterface.java | // Path: src/main/java/com/mde/potdroid/models/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 3L;
//
// private Integer mId;
// private String mNick;
// private String mAvatarFile;
// private Integer mAvatarId;
// private Integer mGroup;
// private Boolean mLocked = false;
//
// public User(Integer id) {
// mId = id;
// }
//
// public String getNick() {
// return mNick;
// }
//
// public void setNick(String nick) {
// mNick = nick;
// }
//
// public String getAvatarFile() {
// return mAvatarFile;
// }
//
// public void setAvatarFile(String avatar) {
// mAvatarFile = avatar;
// }
//
// public Integer getAvatarId() {
// return mAvatarId;
// }
//
// public void setAvatarId(Integer id) {
// mAvatarId = id;
// }
//
// public Integer getGroup() {
// return mGroup;
// }
//
// public void setGroup(Integer group) {
// mGroup = group;
// }
//
// public Integer getId() {
// return mId;
// }
//
// public void setLocked(boolean locked) {
// mLocked = locked;
// }
//
// public boolean getLocked() {
// return mLocked;
// }
// }
| import android.app.Activity;
import android.support.annotation.Keep;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import com.mde.potdroid.models.User; | * Return if Benders can be downloaded
*
* @return true if enabled
*/
@JavascriptInterface
public boolean downloadBenders() {
return mSettings.downloadBenders();
}
/**
* Return the bender position
*
* @return 0 -> never, 1 -> always posthead, 2 -> always postbody, 3 -> orientation dependent
*/
@JavascriptInterface
public int getBenderPosition() {
return mSettings.benderPosition();
}
/**
* Return an url (filepath) to a bender
*
* @param user_id the user id of the User whose Bender is requested
* @param avatar_file The filename of the respective bender
* @param avatar_id the ID of the bender
*/
@JavascriptInterface
public void displayBender(final int user_id, String avatar_file, int avatar_id) {
// this is needed, because we want to load asynchroneously. | // Path: src/main/java/com/mde/potdroid/models/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 3L;
//
// private Integer mId;
// private String mNick;
// private String mAvatarFile;
// private Integer mAvatarId;
// private Integer mGroup;
// private Boolean mLocked = false;
//
// public User(Integer id) {
// mId = id;
// }
//
// public String getNick() {
// return mNick;
// }
//
// public void setNick(String nick) {
// mNick = nick;
// }
//
// public String getAvatarFile() {
// return mAvatarFile;
// }
//
// public void setAvatarFile(String avatar) {
// mAvatarFile = avatar;
// }
//
// public Integer getAvatarId() {
// return mAvatarId;
// }
//
// public void setAvatarId(Integer id) {
// mAvatarId = id;
// }
//
// public Integer getGroup() {
// return mGroup;
// }
//
// public void setGroup(Integer group) {
// mGroup = group;
// }
//
// public Integer getId() {
// return mId;
// }
//
// public void setLocked(boolean locked) {
// mLocked = locked;
// }
//
// public boolean getLocked() {
// return mLocked;
// }
// }
// Path: src/main/java/com/mde/potdroid/helpers/BenderJSInterface.java
import android.app.Activity;
import android.support.annotation.Keep;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import com.mde.potdroid.models.User;
* Return if Benders can be downloaded
*
* @return true if enabled
*/
@JavascriptInterface
public boolean downloadBenders() {
return mSettings.downloadBenders();
}
/**
* Return the bender position
*
* @return 0 -> never, 1 -> always posthead, 2 -> always postbody, 3 -> orientation dependent
*/
@JavascriptInterface
public int getBenderPosition() {
return mSettings.benderPosition();
}
/**
* Return an url (filepath) to a bender
*
* @param user_id the user id of the User whose Bender is requested
* @param avatar_file The filename of the respective bender
* @param avatar_id the ID of the bender
*/
@JavascriptInterface
public void displayBender(final int user_id, String avatar_file, int avatar_id) {
// this is needed, because we want to load asynchroneously. | User u = new User(user_id); |
janoliver/pOT-Droid | src/main/java/com/mde/potdroid/helpers/BenderHandler.java | // Path: src/main/java/com/mde/potdroid/models/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 3L;
//
// private Integer mId;
// private String mNick;
// private String mAvatarFile;
// private Integer mAvatarId;
// private Integer mGroup;
// private Boolean mLocked = false;
//
// public User(Integer id) {
// mId = id;
// }
//
// public String getNick() {
// return mNick;
// }
//
// public void setNick(String nick) {
// mNick = nick;
// }
//
// public String getAvatarFile() {
// return mAvatarFile;
// }
//
// public void setAvatarFile(String avatar) {
// mAvatarFile = avatar;
// }
//
// public Integer getAvatarId() {
// return mAvatarId;
// }
//
// public void setAvatarId(Integer id) {
// mAvatarId = id;
// }
//
// public Integer getGroup() {
// return mGroup;
// }
//
// public void setGroup(Integer group) {
// mGroup = group;
// }
//
// public Integer getId() {
// return mId;
// }
//
// public void setLocked(boolean locked) {
// mLocked = locked;
// }
//
// public boolean getLocked() {
// return mLocked;
// }
// }
| import android.content.Context;
import android.text.TextUtils;
import com.mde.potdroid.models.User;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List; | package com.mde.potdroid.helpers;
/**
* This class handles the Bender downloading and storing the User <-> Bender
* information in the database.
*/
public class BenderHandler {
// the context
private Context mContext;
// access to the app settings
private SettingsWrapper mSettings;
// the database wrapper, so we can store the bender information
private DatabaseWrapper mDatabase;
public BenderHandler(Context cx) {
mContext = cx;
mSettings = new SettingsWrapper(cx);
mDatabase = new DatabaseWrapper(cx);
}
/**
* Get the path to the avatar of User user. If the user object has an Avatar field set,
* this is taken (and, if needed, downloaded). If not, we look for the last seen
* avatar of this user in the Database. If this is not available either, return null.
*
* @param user User object
* @param callback Callback
*/ | // Path: src/main/java/com/mde/potdroid/models/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 3L;
//
// private Integer mId;
// private String mNick;
// private String mAvatarFile;
// private Integer mAvatarId;
// private Integer mGroup;
// private Boolean mLocked = false;
//
// public User(Integer id) {
// mId = id;
// }
//
// public String getNick() {
// return mNick;
// }
//
// public void setNick(String nick) {
// mNick = nick;
// }
//
// public String getAvatarFile() {
// return mAvatarFile;
// }
//
// public void setAvatarFile(String avatar) {
// mAvatarFile = avatar;
// }
//
// public Integer getAvatarId() {
// return mAvatarId;
// }
//
// public void setAvatarId(Integer id) {
// mAvatarId = id;
// }
//
// public Integer getGroup() {
// return mGroup;
// }
//
// public void setGroup(Integer group) {
// mGroup = group;
// }
//
// public Integer getId() {
// return mId;
// }
//
// public void setLocked(boolean locked) {
// mLocked = locked;
// }
//
// public boolean getLocked() {
// return mLocked;
// }
// }
// Path: src/main/java/com/mde/potdroid/helpers/BenderHandler.java
import android.content.Context;
import android.text.TextUtils;
import com.mde.potdroid.models.User;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
package com.mde.potdroid.helpers;
/**
* This class handles the Bender downloading and storing the User <-> Bender
* information in the database.
*/
public class BenderHandler {
// the context
private Context mContext;
// access to the app settings
private SettingsWrapper mSettings;
// the database wrapper, so we can store the bender information
private DatabaseWrapper mDatabase;
public BenderHandler(Context cx) {
mContext = cx;
mSettings = new SettingsWrapper(cx);
mDatabase = new DatabaseWrapper(cx);
}
/**
* Get the path to the avatar of User user. If the user object has an Avatar field set,
* this is taken (and, if needed, downloaded). If not, we look for the last seen
* avatar of this user in the Database. If this is not available either, return null.
*
* @param user User object
* @param callback Callback
*/ | public void getAvatar(final User user, final BenderListener callback) { |
janoliver/pOT-Droid | src/main/java/com/mde/potdroid/helpers/MessageBuilder.java | // Path: src/main/java/com/mde/potdroid/models/Message.java
// public class Message {
//
// private static final long serialVersionUID = 9L;
//
// private Integer mId;
// private String mTitle;
// private String mText;
// private Date mDate;
// private User mFrom;
// private Boolean mOutgoing;
// private Boolean mUnread;
// private Boolean mSystem = false;
// private String mHtmlCache;
//
// public Integer getId() {
// return mId;
// }
//
// public void setId(Integer id) {
// this.mId = id;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public void setTitle(String title) {
// this.mTitle = title;
// }
//
// public String getText() {
// return mText;
// }
//
// public void setText(String text) {
// this.mText = text;
// }
//
// public Date getDate() {
// return mDate;
// }
//
// public void setDate(Date date) {
// this.mDate = date;
// }
//
// public User getFrom() {
// return mFrom;
// }
//
// public void setFrom(User from) {
// this.mFrom = from;
// }
//
// public Boolean isUnread() {
// return mUnread;
// }
//
// public Boolean isOutgoing() {
// return mOutgoing;
// }
//
// public Boolean isSystem() {
// return mSystem;
// }
//
// public void setHtmlCache(String cache) {
// mHtmlCache = cache;
// }
//
// public String getHtmlCache() {
// return mHtmlCache;
// }
//
// public void setOutgoing(Boolean out) {
// mOutgoing = out;
// }
//
// public void setUnread(Boolean unread) {
// mUnread = unread;
// }
//
// public void setSystem(Boolean system) {
// mSystem = system;
// }
//
// public boolean isReply() {
// return mTitle.length() > 3 && mTitle.substring(0, 3).equals("Re:");
// }
//
// }
| import android.content.Context;
import android.content.res.Configuration;
import android.support.annotation.Keep;
import com.mde.potdroid.R;
import com.mde.potdroid.models.Message;
import com.samskivert.mustache.Mustache;
import java.io.*; | package com.mde.potdroid.helpers;
/**
* This class, given a Message object, turns it into displayable HTML code
* for the WebView we use.
*/
public class MessageBuilder {
// a reference to the context
private Context mContext;
private SettingsWrapper mSettings;
private BenderHandler mBenderHandler;
public MessageBuilder(Context cx) {
mContext = cx;
mSettings = new SettingsWrapper(cx);
mBenderHandler = new BenderHandler(cx);
}
/**
* Parse a message object to HTML using JMoustache template engine.
*
* @param message the Message object
* @return HTML code
* @throws IOException
*/ | // Path: src/main/java/com/mde/potdroid/models/Message.java
// public class Message {
//
// private static final long serialVersionUID = 9L;
//
// private Integer mId;
// private String mTitle;
// private String mText;
// private Date mDate;
// private User mFrom;
// private Boolean mOutgoing;
// private Boolean mUnread;
// private Boolean mSystem = false;
// private String mHtmlCache;
//
// public Integer getId() {
// return mId;
// }
//
// public void setId(Integer id) {
// this.mId = id;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public void setTitle(String title) {
// this.mTitle = title;
// }
//
// public String getText() {
// return mText;
// }
//
// public void setText(String text) {
// this.mText = text;
// }
//
// public Date getDate() {
// return mDate;
// }
//
// public void setDate(Date date) {
// this.mDate = date;
// }
//
// public User getFrom() {
// return mFrom;
// }
//
// public void setFrom(User from) {
// this.mFrom = from;
// }
//
// public Boolean isUnread() {
// return mUnread;
// }
//
// public Boolean isOutgoing() {
// return mOutgoing;
// }
//
// public Boolean isSystem() {
// return mSystem;
// }
//
// public void setHtmlCache(String cache) {
// mHtmlCache = cache;
// }
//
// public String getHtmlCache() {
// return mHtmlCache;
// }
//
// public void setOutgoing(Boolean out) {
// mOutgoing = out;
// }
//
// public void setUnread(Boolean unread) {
// mUnread = unread;
// }
//
// public void setSystem(Boolean system) {
// mSystem = system;
// }
//
// public boolean isReply() {
// return mTitle.length() > 3 && mTitle.substring(0, 3).equals("Re:");
// }
//
// }
// Path: src/main/java/com/mde/potdroid/helpers/MessageBuilder.java
import android.content.Context;
import android.content.res.Configuration;
import android.support.annotation.Keep;
import com.mde.potdroid.R;
import com.mde.potdroid.models.Message;
import com.samskivert.mustache.Mustache;
import java.io.*;
package com.mde.potdroid.helpers;
/**
* This class, given a Message object, turns it into displayable HTML code
* for the WebView we use.
*/
public class MessageBuilder {
// a reference to the context
private Context mContext;
private SettingsWrapper mSettings;
private BenderHandler mBenderHandler;
public MessageBuilder(Context cx) {
mContext = cx;
mSettings = new SettingsWrapper(cx);
mBenderHandler = new BenderHandler(cx);
}
/**
* Parse a message object to HTML using JMoustache template engine.
*
* @param message the Message object
* @return HTML code
* @throws IOException
*/ | public String parse(Message message) throws IOException { |
janoliver/pOT-Droid | src/main/java/com/mde/potdroid/parsers/MessageListParser.java | // Path: src/main/java/com/mde/potdroid/models/Message.java
// public class Message {
//
// private static final long serialVersionUID = 9L;
//
// private Integer mId;
// private String mTitle;
// private String mText;
// private Date mDate;
// private User mFrom;
// private Boolean mOutgoing;
// private Boolean mUnread;
// private Boolean mSystem = false;
// private String mHtmlCache;
//
// public Integer getId() {
// return mId;
// }
//
// public void setId(Integer id) {
// this.mId = id;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public void setTitle(String title) {
// this.mTitle = title;
// }
//
// public String getText() {
// return mText;
// }
//
// public void setText(String text) {
// this.mText = text;
// }
//
// public Date getDate() {
// return mDate;
// }
//
// public void setDate(Date date) {
// this.mDate = date;
// }
//
// public User getFrom() {
// return mFrom;
// }
//
// public void setFrom(User from) {
// this.mFrom = from;
// }
//
// public Boolean isUnread() {
// return mUnread;
// }
//
// public Boolean isOutgoing() {
// return mOutgoing;
// }
//
// public Boolean isSystem() {
// return mSystem;
// }
//
// public void setHtmlCache(String cache) {
// mHtmlCache = cache;
// }
//
// public String getHtmlCache() {
// return mHtmlCache;
// }
//
// public void setOutgoing(Boolean out) {
// mOutgoing = out;
// }
//
// public void setUnread(Boolean unread) {
// mUnread = unread;
// }
//
// public void setSystem(Boolean system) {
// mSystem = system;
// }
//
// public boolean isReply() {
// return mTitle.length() > 3 && mTitle.substring(0, 3).equals("Re:");
// }
//
// }
//
// Path: src/main/java/com/mde/potdroid/models/MessageList.java
// public class MessageList {
//
// private static final long serialVersionUID = 10L;
//
// private Integer mNumberOfUnreadMessages;
// private ArrayList<Message> mMessages = new ArrayList<Message>();
//
// public static final String TAG_INBOX = "inbox";
// public static final String TAG_OUTBOX = "outbox";
//
// public Integer getNumberOfMessages() {
// return mMessages.size();
// }
//
// public ArrayList<Message> getMessages() {
// return mMessages;
// }
//
// public void addMessage(Message message) {
// this.mMessages.add(message);
// }
//
// public Integer getNumberOfUnreadMessages() {
// return mNumberOfUnreadMessages;
// }
//
// public void setNumberOfUnreadMessages(Integer numberOfUnreadMessages) {
// mNumberOfUnreadMessages = numberOfUnreadMessages;
// }
//
// public ArrayList<Message> getUnreadMessages() {
// ArrayList<Message> ret = new ArrayList<Message>();
// for (Message m : getMessages())
// if (m.isUnread())
// ret.add(m);
// return ret;
// }
//
// }
//
// Path: src/main/java/com/mde/potdroid/models/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 3L;
//
// private Integer mId;
// private String mNick;
// private String mAvatarFile;
// private Integer mAvatarId;
// private Integer mGroup;
// private Boolean mLocked = false;
//
// public User(Integer id) {
// mId = id;
// }
//
// public String getNick() {
// return mNick;
// }
//
// public void setNick(String nick) {
// mNick = nick;
// }
//
// public String getAvatarFile() {
// return mAvatarFile;
// }
//
// public void setAvatarFile(String avatar) {
// mAvatarFile = avatar;
// }
//
// public Integer getAvatarId() {
// return mAvatarId;
// }
//
// public void setAvatarId(Integer id) {
// mAvatarId = id;
// }
//
// public Integer getGroup() {
// return mGroup;
// }
//
// public void setGroup(Integer group) {
// mGroup = group;
// }
//
// public Integer getId() {
// return mId;
// }
//
// public void setLocked(boolean locked) {
// mLocked = locked;
// }
//
// public boolean getLocked() {
// return mLocked;
// }
// }
| import com.mde.potdroid.models.Message;
import com.mde.potdroid.models.MessageList;
import com.mde.potdroid.models.User;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package com.mde.potdroid.parsers;
/**
* HTML Parser for the PM message list.
*/
public class MessageListParser {
public static final String INBOX_URL = "pm/?a=0&cid=1";
public static final String OUTBOX_URL = "pm/?a=0&cid=2"; | // Path: src/main/java/com/mde/potdroid/models/Message.java
// public class Message {
//
// private static final long serialVersionUID = 9L;
//
// private Integer mId;
// private String mTitle;
// private String mText;
// private Date mDate;
// private User mFrom;
// private Boolean mOutgoing;
// private Boolean mUnread;
// private Boolean mSystem = false;
// private String mHtmlCache;
//
// public Integer getId() {
// return mId;
// }
//
// public void setId(Integer id) {
// this.mId = id;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public void setTitle(String title) {
// this.mTitle = title;
// }
//
// public String getText() {
// return mText;
// }
//
// public void setText(String text) {
// this.mText = text;
// }
//
// public Date getDate() {
// return mDate;
// }
//
// public void setDate(Date date) {
// this.mDate = date;
// }
//
// public User getFrom() {
// return mFrom;
// }
//
// public void setFrom(User from) {
// this.mFrom = from;
// }
//
// public Boolean isUnread() {
// return mUnread;
// }
//
// public Boolean isOutgoing() {
// return mOutgoing;
// }
//
// public Boolean isSystem() {
// return mSystem;
// }
//
// public void setHtmlCache(String cache) {
// mHtmlCache = cache;
// }
//
// public String getHtmlCache() {
// return mHtmlCache;
// }
//
// public void setOutgoing(Boolean out) {
// mOutgoing = out;
// }
//
// public void setUnread(Boolean unread) {
// mUnread = unread;
// }
//
// public void setSystem(Boolean system) {
// mSystem = system;
// }
//
// public boolean isReply() {
// return mTitle.length() > 3 && mTitle.substring(0, 3).equals("Re:");
// }
//
// }
//
// Path: src/main/java/com/mde/potdroid/models/MessageList.java
// public class MessageList {
//
// private static final long serialVersionUID = 10L;
//
// private Integer mNumberOfUnreadMessages;
// private ArrayList<Message> mMessages = new ArrayList<Message>();
//
// public static final String TAG_INBOX = "inbox";
// public static final String TAG_OUTBOX = "outbox";
//
// public Integer getNumberOfMessages() {
// return mMessages.size();
// }
//
// public ArrayList<Message> getMessages() {
// return mMessages;
// }
//
// public void addMessage(Message message) {
// this.mMessages.add(message);
// }
//
// public Integer getNumberOfUnreadMessages() {
// return mNumberOfUnreadMessages;
// }
//
// public void setNumberOfUnreadMessages(Integer numberOfUnreadMessages) {
// mNumberOfUnreadMessages = numberOfUnreadMessages;
// }
//
// public ArrayList<Message> getUnreadMessages() {
// ArrayList<Message> ret = new ArrayList<Message>();
// for (Message m : getMessages())
// if (m.isUnread())
// ret.add(m);
// return ret;
// }
//
// }
//
// Path: src/main/java/com/mde/potdroid/models/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 3L;
//
// private Integer mId;
// private String mNick;
// private String mAvatarFile;
// private Integer mAvatarId;
// private Integer mGroup;
// private Boolean mLocked = false;
//
// public User(Integer id) {
// mId = id;
// }
//
// public String getNick() {
// return mNick;
// }
//
// public void setNick(String nick) {
// mNick = nick;
// }
//
// public String getAvatarFile() {
// return mAvatarFile;
// }
//
// public void setAvatarFile(String avatar) {
// mAvatarFile = avatar;
// }
//
// public Integer getAvatarId() {
// return mAvatarId;
// }
//
// public void setAvatarId(Integer id) {
// mAvatarId = id;
// }
//
// public Integer getGroup() {
// return mGroup;
// }
//
// public void setGroup(Integer group) {
// mGroup = group;
// }
//
// public Integer getId() {
// return mId;
// }
//
// public void setLocked(boolean locked) {
// mLocked = locked;
// }
//
// public boolean getLocked() {
// return mLocked;
// }
// }
// Path: src/main/java/com/mde/potdroid/parsers/MessageListParser.java
import com.mde.potdroid.models.Message;
import com.mde.potdroid.models.MessageList;
import com.mde.potdroid.models.User;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package com.mde.potdroid.parsers;
/**
* HTML Parser for the PM message list.
*/
public class MessageListParser {
public static final String INBOX_URL = "pm/?a=0&cid=1";
public static final String OUTBOX_URL = "pm/?a=0&cid=2"; | private MessageList mMessageList; |
janoliver/pOT-Droid | src/main/java/com/mde/potdroid/parsers/MessageListParser.java | // Path: src/main/java/com/mde/potdroid/models/Message.java
// public class Message {
//
// private static final long serialVersionUID = 9L;
//
// private Integer mId;
// private String mTitle;
// private String mText;
// private Date mDate;
// private User mFrom;
// private Boolean mOutgoing;
// private Boolean mUnread;
// private Boolean mSystem = false;
// private String mHtmlCache;
//
// public Integer getId() {
// return mId;
// }
//
// public void setId(Integer id) {
// this.mId = id;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public void setTitle(String title) {
// this.mTitle = title;
// }
//
// public String getText() {
// return mText;
// }
//
// public void setText(String text) {
// this.mText = text;
// }
//
// public Date getDate() {
// return mDate;
// }
//
// public void setDate(Date date) {
// this.mDate = date;
// }
//
// public User getFrom() {
// return mFrom;
// }
//
// public void setFrom(User from) {
// this.mFrom = from;
// }
//
// public Boolean isUnread() {
// return mUnread;
// }
//
// public Boolean isOutgoing() {
// return mOutgoing;
// }
//
// public Boolean isSystem() {
// return mSystem;
// }
//
// public void setHtmlCache(String cache) {
// mHtmlCache = cache;
// }
//
// public String getHtmlCache() {
// return mHtmlCache;
// }
//
// public void setOutgoing(Boolean out) {
// mOutgoing = out;
// }
//
// public void setUnread(Boolean unread) {
// mUnread = unread;
// }
//
// public void setSystem(Boolean system) {
// mSystem = system;
// }
//
// public boolean isReply() {
// return mTitle.length() > 3 && mTitle.substring(0, 3).equals("Re:");
// }
//
// }
//
// Path: src/main/java/com/mde/potdroid/models/MessageList.java
// public class MessageList {
//
// private static final long serialVersionUID = 10L;
//
// private Integer mNumberOfUnreadMessages;
// private ArrayList<Message> mMessages = new ArrayList<Message>();
//
// public static final String TAG_INBOX = "inbox";
// public static final String TAG_OUTBOX = "outbox";
//
// public Integer getNumberOfMessages() {
// return mMessages.size();
// }
//
// public ArrayList<Message> getMessages() {
// return mMessages;
// }
//
// public void addMessage(Message message) {
// this.mMessages.add(message);
// }
//
// public Integer getNumberOfUnreadMessages() {
// return mNumberOfUnreadMessages;
// }
//
// public void setNumberOfUnreadMessages(Integer numberOfUnreadMessages) {
// mNumberOfUnreadMessages = numberOfUnreadMessages;
// }
//
// public ArrayList<Message> getUnreadMessages() {
// ArrayList<Message> ret = new ArrayList<Message>();
// for (Message m : getMessages())
// if (m.isUnread())
// ret.add(m);
// return ret;
// }
//
// }
//
// Path: src/main/java/com/mde/potdroid/models/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 3L;
//
// private Integer mId;
// private String mNick;
// private String mAvatarFile;
// private Integer mAvatarId;
// private Integer mGroup;
// private Boolean mLocked = false;
//
// public User(Integer id) {
// mId = id;
// }
//
// public String getNick() {
// return mNick;
// }
//
// public void setNick(String nick) {
// mNick = nick;
// }
//
// public String getAvatarFile() {
// return mAvatarFile;
// }
//
// public void setAvatarFile(String avatar) {
// mAvatarFile = avatar;
// }
//
// public Integer getAvatarId() {
// return mAvatarId;
// }
//
// public void setAvatarId(Integer id) {
// mAvatarId = id;
// }
//
// public Integer getGroup() {
// return mGroup;
// }
//
// public void setGroup(Integer group) {
// mGroup = group;
// }
//
// public Integer getId() {
// return mId;
// }
//
// public void setLocked(boolean locked) {
// mLocked = locked;
// }
//
// public boolean getLocked() {
// return mLocked;
// }
// }
| import com.mde.potdroid.models.Message;
import com.mde.potdroid.models.MessageList;
import com.mde.potdroid.models.User;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | + "target='_blank'>([^<]+)</a>|System)</td> <td (class=\"bold\" |)style='width: 15%'>" +
"([.: 0-9]+)</td>");
public MessageListParser() {
mMessageList = new MessageList();
}
public static String getUrl(String mode) {
if (mode.equals(MessageList.TAG_INBOX))
return INBOX_URL;
else
return OUTBOX_URL;
}
public MessageList parse(String html) throws IOException {
Matcher m = mMessagePaggern.matcher(html);
int n_unread = 0;
while (m.find()) {
Message message = new Message();
message.setId(Integer.parseInt(m.group(1)));
message.setTitle(m.group(2));
message.setUnread(m.group(3).compareTo("") != 0);
if (m.group(4).equals("System")) {
message.setSystem(true);
} else {
message.setSystem(false); | // Path: src/main/java/com/mde/potdroid/models/Message.java
// public class Message {
//
// private static final long serialVersionUID = 9L;
//
// private Integer mId;
// private String mTitle;
// private String mText;
// private Date mDate;
// private User mFrom;
// private Boolean mOutgoing;
// private Boolean mUnread;
// private Boolean mSystem = false;
// private String mHtmlCache;
//
// public Integer getId() {
// return mId;
// }
//
// public void setId(Integer id) {
// this.mId = id;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public void setTitle(String title) {
// this.mTitle = title;
// }
//
// public String getText() {
// return mText;
// }
//
// public void setText(String text) {
// this.mText = text;
// }
//
// public Date getDate() {
// return mDate;
// }
//
// public void setDate(Date date) {
// this.mDate = date;
// }
//
// public User getFrom() {
// return mFrom;
// }
//
// public void setFrom(User from) {
// this.mFrom = from;
// }
//
// public Boolean isUnread() {
// return mUnread;
// }
//
// public Boolean isOutgoing() {
// return mOutgoing;
// }
//
// public Boolean isSystem() {
// return mSystem;
// }
//
// public void setHtmlCache(String cache) {
// mHtmlCache = cache;
// }
//
// public String getHtmlCache() {
// return mHtmlCache;
// }
//
// public void setOutgoing(Boolean out) {
// mOutgoing = out;
// }
//
// public void setUnread(Boolean unread) {
// mUnread = unread;
// }
//
// public void setSystem(Boolean system) {
// mSystem = system;
// }
//
// public boolean isReply() {
// return mTitle.length() > 3 && mTitle.substring(0, 3).equals("Re:");
// }
//
// }
//
// Path: src/main/java/com/mde/potdroid/models/MessageList.java
// public class MessageList {
//
// private static final long serialVersionUID = 10L;
//
// private Integer mNumberOfUnreadMessages;
// private ArrayList<Message> mMessages = new ArrayList<Message>();
//
// public static final String TAG_INBOX = "inbox";
// public static final String TAG_OUTBOX = "outbox";
//
// public Integer getNumberOfMessages() {
// return mMessages.size();
// }
//
// public ArrayList<Message> getMessages() {
// return mMessages;
// }
//
// public void addMessage(Message message) {
// this.mMessages.add(message);
// }
//
// public Integer getNumberOfUnreadMessages() {
// return mNumberOfUnreadMessages;
// }
//
// public void setNumberOfUnreadMessages(Integer numberOfUnreadMessages) {
// mNumberOfUnreadMessages = numberOfUnreadMessages;
// }
//
// public ArrayList<Message> getUnreadMessages() {
// ArrayList<Message> ret = new ArrayList<Message>();
// for (Message m : getMessages())
// if (m.isUnread())
// ret.add(m);
// return ret;
// }
//
// }
//
// Path: src/main/java/com/mde/potdroid/models/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 3L;
//
// private Integer mId;
// private String mNick;
// private String mAvatarFile;
// private Integer mAvatarId;
// private Integer mGroup;
// private Boolean mLocked = false;
//
// public User(Integer id) {
// mId = id;
// }
//
// public String getNick() {
// return mNick;
// }
//
// public void setNick(String nick) {
// mNick = nick;
// }
//
// public String getAvatarFile() {
// return mAvatarFile;
// }
//
// public void setAvatarFile(String avatar) {
// mAvatarFile = avatar;
// }
//
// public Integer getAvatarId() {
// return mAvatarId;
// }
//
// public void setAvatarId(Integer id) {
// mAvatarId = id;
// }
//
// public Integer getGroup() {
// return mGroup;
// }
//
// public void setGroup(Integer group) {
// mGroup = group;
// }
//
// public Integer getId() {
// return mId;
// }
//
// public void setLocked(boolean locked) {
// mLocked = locked;
// }
//
// public boolean getLocked() {
// return mLocked;
// }
// }
// Path: src/main/java/com/mde/potdroid/parsers/MessageListParser.java
import com.mde.potdroid.models.Message;
import com.mde.potdroid.models.MessageList;
import com.mde.potdroid.models.User;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+ "target='_blank'>([^<]+)</a>|System)</td> <td (class=\"bold\" |)style='width: 15%'>" +
"([.: 0-9]+)</td>");
public MessageListParser() {
mMessageList = new MessageList();
}
public static String getUrl(String mode) {
if (mode.equals(MessageList.TAG_INBOX))
return INBOX_URL;
else
return OUTBOX_URL;
}
public MessageList parse(String html) throws IOException {
Matcher m = mMessagePaggern.matcher(html);
int n_unread = 0;
while (m.find()) {
Message message = new Message();
message.setId(Integer.parseInt(m.group(1)));
message.setTitle(m.group(2));
message.setUnread(m.group(3).compareTo("") != 0);
if (m.group(4).equals("System")) {
message.setSystem(true);
} else {
message.setSystem(false); | User author = new User(Integer.parseInt(m.group(5))); |
janoliver/pOT-Droid | src/main/java/com/mde/potdroid/AboutActivity.java | // Path: src/main/java/com/mde/potdroid/fragments/AboutFragment.java
// public class AboutFragment extends BaseFragment {
//
// /**
// * Create a new instance of AboutFragment and set the arguments
// *
// * @return AboutFragment instance
// */
// public static AboutFragment newInstance() {
// return new AboutFragment();
// }
//
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setHasOptionsMenu(true);
// }
//
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saved) {
// View v = inflater.inflate(R.layout.layout_about, container, false);
// WebView webView = (WebView) v.findViewById(R.id.about);
// webView.getSettings().setDefaultFontSize(mSettings.getDefaultFontSize());
// try {
// webView.loadDataWithBaseURL("file:///android_asset/", getAboutHtml(),
// "text/html", Network.ENCODING_UTF8, null);
// } catch (IOException e) {
// // passiert nicht! :mad:
// }
//
// return v;
// }
//
// public String getAboutHtml() throws IOException {
// InputStream is = getActivity().getResources().getAssets().open("about.html");
// Reader reader = new InputStreamReader(is);
// StringWriter sw = new StringWriter();
// Mustache.compiler().compile(reader).execute(new AboutContext(getActivity()), sw);
// return sw.toString();
// }
//
// @Keep
// public static class AboutContext {
// protected Activity mActivity;
// private CssStyleWrapper mStyle;
//
// public AboutContext(Activity act) {
// mActivity = act;
// mStyle = new CssStyleWrapper(act);
// }
//
// public CssStyleWrapper getStyle() {
// return mStyle;
// }
//
// public String getVersionString() {
// String version;
// try {
// version = mActivity.getPackageManager().getPackageInfo(mActivity.getPackageName(), 0).versionName;
// } catch (PackageManager.NameNotFoundException e) {
// version = "";
// }
// return version;
// }
//
// public Integer getVersionCode() {
// Integer version;
// try {
// version = mActivity.getPackageManager().getPackageInfo(mActivity.getPackageName(), 0).versionCode;
// } catch (PackageManager.NameNotFoundException e) {
// version = 0;
// }
// return version;
// }
//
// public String getAndroidVersion() {
// return Build.VERSION.RELEASE;
// }
//
// public Integer getDensity() {
// DisplayMetrics metrics = mActivity.getResources().getDisplayMetrics();
// return (int) (metrics.density * 160f);
// }
//
// }
//
//
// }
| import android.os.Bundle;
import com.mde.potdroid.fragments.AboutFragment; | package com.mde.potdroid;
/**
* The Activity that contains a AboutFragment. It handles some callbacks of the
* Formlistener after Post submission.
*/
public class AboutActivity extends BaseActivity {
private static final String FRAGMENT_TAG = "about";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// create and add the fragment | // Path: src/main/java/com/mde/potdroid/fragments/AboutFragment.java
// public class AboutFragment extends BaseFragment {
//
// /**
// * Create a new instance of AboutFragment and set the arguments
// *
// * @return AboutFragment instance
// */
// public static AboutFragment newInstance() {
// return new AboutFragment();
// }
//
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// setHasOptionsMenu(true);
// }
//
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saved) {
// View v = inflater.inflate(R.layout.layout_about, container, false);
// WebView webView = (WebView) v.findViewById(R.id.about);
// webView.getSettings().setDefaultFontSize(mSettings.getDefaultFontSize());
// try {
// webView.loadDataWithBaseURL("file:///android_asset/", getAboutHtml(),
// "text/html", Network.ENCODING_UTF8, null);
// } catch (IOException e) {
// // passiert nicht! :mad:
// }
//
// return v;
// }
//
// public String getAboutHtml() throws IOException {
// InputStream is = getActivity().getResources().getAssets().open("about.html");
// Reader reader = new InputStreamReader(is);
// StringWriter sw = new StringWriter();
// Mustache.compiler().compile(reader).execute(new AboutContext(getActivity()), sw);
// return sw.toString();
// }
//
// @Keep
// public static class AboutContext {
// protected Activity mActivity;
// private CssStyleWrapper mStyle;
//
// public AboutContext(Activity act) {
// mActivity = act;
// mStyle = new CssStyleWrapper(act);
// }
//
// public CssStyleWrapper getStyle() {
// return mStyle;
// }
//
// public String getVersionString() {
// String version;
// try {
// version = mActivity.getPackageManager().getPackageInfo(mActivity.getPackageName(), 0).versionName;
// } catch (PackageManager.NameNotFoundException e) {
// version = "";
// }
// return version;
// }
//
// public Integer getVersionCode() {
// Integer version;
// try {
// version = mActivity.getPackageManager().getPackageInfo(mActivity.getPackageName(), 0).versionCode;
// } catch (PackageManager.NameNotFoundException e) {
// version = 0;
// }
// return version;
// }
//
// public String getAndroidVersion() {
// return Build.VERSION.RELEASE;
// }
//
// public Integer getDensity() {
// DisplayMetrics metrics = mActivity.getResources().getDisplayMetrics();
// return (int) (metrics.density * 160f);
// }
//
// }
//
//
// }
// Path: src/main/java/com/mde/potdroid/AboutActivity.java
import android.os.Bundle;
import com.mde.potdroid.fragments.AboutFragment;
package com.mde.potdroid;
/**
* The Activity that contains a AboutFragment. It handles some callbacks of the
* Formlistener after Post submission.
*/
public class AboutActivity extends BaseActivity {
private static final String FRAGMENT_TAG = "about";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// create and add the fragment | AboutFragment fragment = (AboutFragment) getSupportFragmentManager() |
janoliver/pOT-Droid | src/main/java/com/mde/potdroid/helpers/CustomExceptionHandler.java | // Path: src/main/java/com/mde/potdroid/helpers/Utils.java
// protected static Context mContext;
| import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import static com.mde.potdroid.helpers.Utils.mContext; | package com.mde.potdroid.helpers;
/**
* This class writes an exception to the SDCard and then forwards the Exception to
* the usual exception handler.
*/
public class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {
// forward to the one before.
private Thread.UncaughtExceptionHandler mDefaultHandler;
public CustomExceptionHandler() {
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
}
@Override
public void uncaughtException(Thread t, Throwable e) {
writeExceptionToSdCard(e);
// forward the exception to the usual Handler
mDefaultHandler.uncaughtException(t, e);
}
public static void writeExceptionToSdCard(Throwable e) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
Date date = new Date();
// save stack trace to string
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
String stacktrace = result.toString();
printWriter.close();
// save string to file
String filename = dateFormat.format(date) + ".stacktrace";
| // Path: src/main/java/com/mde/potdroid/helpers/Utils.java
// protected static Context mContext;
// Path: src/main/java/com/mde/potdroid/helpers/CustomExceptionHandler.java
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import static com.mde.potdroid.helpers.Utils.mContext;
package com.mde.potdroid.helpers;
/**
* This class writes an exception to the SDCard and then forwards the Exception to
* the usual exception handler.
*/
public class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {
// forward to the one before.
private Thread.UncaughtExceptionHandler mDefaultHandler;
public CustomExceptionHandler() {
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
}
@Override
public void uncaughtException(Thread t, Throwable e) {
writeExceptionToSdCard(e);
// forward the exception to the usual Handler
mDefaultHandler.uncaughtException(t, e);
}
public static void writeExceptionToSdCard(Throwable e) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
Date date = new Date();
// save stack trace to string
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
String stacktrace = result.toString();
printWriter.close();
// save string to file
String filename = dateFormat.format(date) + ".stacktrace";
| File path = new File(mContext.getExternalFilesDir(null), "log"); |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/service/impl/CategoryServiceImpl.java | // Path: src/main/java/yourwebproject2/framework/data/BaseJPAServiceImpl.java
// public abstract class BaseJPAServiceImpl<T extends Entity, ID extends Serializable> implements BaseService<T, ID> {
// protected BaseJPARepository<T, ID> baseJpaRepository;
// protected Class<T> entityClass;
//
// public T insert(T object) throws Exception {
// return baseJpaRepository.insert(object);
// }
//
// public T update(T object) throws Exception {
// return baseJpaRepository.update(object);
// }
//
// public void delete(T object) throws Exception {
// baseJpaRepository.delete(object);
// }
//
// public T findById(ID id) throws Exception {
// T result = baseJpaRepository.findById(id);
//
// if (result != null)
// return result;
// else
// throw new Exception("Not Found");
// }
//
// public Collection<T> findAllByPage(int pageNum, int countPerPage, Order order) throws Exception {
// return null; //To change body of implemented methods use File | Settings | File Templates.
// }
// }
//
// Path: src/main/java/yourwebproject2/framework/exception/NotFoundException.java
// public class NotFoundException extends Exception {
// public NotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/Category.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="priority_idx", columnList = "priority"),
// @Index(name="parentCategory_idx", columnList = "parent_category")})
// public class Category extends JPAEntity<Long> {
// private String name;
// private Integer priority;
// private Category parentCategory;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @NotNull
// @Column
// public Integer getPriority() {
// return priority;
// }
//
// public void setPriority(Integer priority) {
// this.priority = priority;
// }
//
// @ManyToOne(fetch = FetchType.EAGER)
// public Category getParentCategory() {
// return parentCategory;
// }
//
// public void setParentCategory(Category parentCategory) {
// this.parentCategory = parentCategory;
// }
//
// @Override
// public String toString() {
// return "Category{" +
// "name='" + name + '\'' +
// ", priority=" + priority +
// ", parentCategory=" + parentCategory +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/CategoryRepository.java
// public interface CategoryRepository extends BaseJPARepository<Category, Long> {
// /**
// * Finds a category with the given categoryName
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName);
//
// /**
// * Finds a category with the given categoryPriority
// *
// * @param categoryPriority
// * @return
// */
// public Category findByCategoryPriority(Integer categoryPriority);
//
// /**
// * Finds sub categories with the given parentCategory
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory);
// }
//
// Path: src/main/java/yourwebproject2/service/CategoryService.java
// public interface CategoryService extends BaseService<Category, Long> {
// /**
// * Validates whether the given category already
// * exists in the system.
// *
// * @param categoryName
// *
// * @return
// */
// public boolean isCategoryPresent(String categoryName);
//
// /**
// * Validates whether the given category priority already
// * exists in the system.
// *
// * @param priorityId
// *
// * @return
// */
// public boolean isPriorityPresent(Integer priorityId);
//
// /**
// * Find category by name
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName) throws NotFoundException;
//
// /**
// * Find sub categories by parent category
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory) throws NotFoundException;
// }
| import yourwebproject2.framework.data.BaseJPAServiceImpl;
import yourwebproject2.framework.exception.NotFoundException;
import yourwebproject2.model.entity.Category;
import yourwebproject2.model.repository.CategoryRepository;
import yourwebproject2.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.List; | package yourwebproject2.service.impl;
/**
* Created by Y.Kamesh on 8/2/2015.
*/
@Service
@Transactional | // Path: src/main/java/yourwebproject2/framework/data/BaseJPAServiceImpl.java
// public abstract class BaseJPAServiceImpl<T extends Entity, ID extends Serializable> implements BaseService<T, ID> {
// protected BaseJPARepository<T, ID> baseJpaRepository;
// protected Class<T> entityClass;
//
// public T insert(T object) throws Exception {
// return baseJpaRepository.insert(object);
// }
//
// public T update(T object) throws Exception {
// return baseJpaRepository.update(object);
// }
//
// public void delete(T object) throws Exception {
// baseJpaRepository.delete(object);
// }
//
// public T findById(ID id) throws Exception {
// T result = baseJpaRepository.findById(id);
//
// if (result != null)
// return result;
// else
// throw new Exception("Not Found");
// }
//
// public Collection<T> findAllByPage(int pageNum, int countPerPage, Order order) throws Exception {
// return null; //To change body of implemented methods use File | Settings | File Templates.
// }
// }
//
// Path: src/main/java/yourwebproject2/framework/exception/NotFoundException.java
// public class NotFoundException extends Exception {
// public NotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/Category.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="priority_idx", columnList = "priority"),
// @Index(name="parentCategory_idx", columnList = "parent_category")})
// public class Category extends JPAEntity<Long> {
// private String name;
// private Integer priority;
// private Category parentCategory;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @NotNull
// @Column
// public Integer getPriority() {
// return priority;
// }
//
// public void setPriority(Integer priority) {
// this.priority = priority;
// }
//
// @ManyToOne(fetch = FetchType.EAGER)
// public Category getParentCategory() {
// return parentCategory;
// }
//
// public void setParentCategory(Category parentCategory) {
// this.parentCategory = parentCategory;
// }
//
// @Override
// public String toString() {
// return "Category{" +
// "name='" + name + '\'' +
// ", priority=" + priority +
// ", parentCategory=" + parentCategory +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/CategoryRepository.java
// public interface CategoryRepository extends BaseJPARepository<Category, Long> {
// /**
// * Finds a category with the given categoryName
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName);
//
// /**
// * Finds a category with the given categoryPriority
// *
// * @param categoryPriority
// * @return
// */
// public Category findByCategoryPriority(Integer categoryPriority);
//
// /**
// * Finds sub categories with the given parentCategory
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory);
// }
//
// Path: src/main/java/yourwebproject2/service/CategoryService.java
// public interface CategoryService extends BaseService<Category, Long> {
// /**
// * Validates whether the given category already
// * exists in the system.
// *
// * @param categoryName
// *
// * @return
// */
// public boolean isCategoryPresent(String categoryName);
//
// /**
// * Validates whether the given category priority already
// * exists in the system.
// *
// * @param priorityId
// *
// * @return
// */
// public boolean isPriorityPresent(Integer priorityId);
//
// /**
// * Find category by name
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName) throws NotFoundException;
//
// /**
// * Find sub categories by parent category
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory) throws NotFoundException;
// }
// Path: src/main/java/yourwebproject2/service/impl/CategoryServiceImpl.java
import yourwebproject2.framework.data.BaseJPAServiceImpl;
import yourwebproject2.framework.exception.NotFoundException;
import yourwebproject2.model.entity.Category;
import yourwebproject2.model.repository.CategoryRepository;
import yourwebproject2.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.List;
package yourwebproject2.service.impl;
/**
* Created by Y.Kamesh on 8/2/2015.
*/
@Service
@Transactional | public class CategoryServiceImpl extends BaseJPAServiceImpl<Category, Long> implements CategoryService { |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/service/impl/CategoryServiceImpl.java | // Path: src/main/java/yourwebproject2/framework/data/BaseJPAServiceImpl.java
// public abstract class BaseJPAServiceImpl<T extends Entity, ID extends Serializable> implements BaseService<T, ID> {
// protected BaseJPARepository<T, ID> baseJpaRepository;
// protected Class<T> entityClass;
//
// public T insert(T object) throws Exception {
// return baseJpaRepository.insert(object);
// }
//
// public T update(T object) throws Exception {
// return baseJpaRepository.update(object);
// }
//
// public void delete(T object) throws Exception {
// baseJpaRepository.delete(object);
// }
//
// public T findById(ID id) throws Exception {
// T result = baseJpaRepository.findById(id);
//
// if (result != null)
// return result;
// else
// throw new Exception("Not Found");
// }
//
// public Collection<T> findAllByPage(int pageNum, int countPerPage, Order order) throws Exception {
// return null; //To change body of implemented methods use File | Settings | File Templates.
// }
// }
//
// Path: src/main/java/yourwebproject2/framework/exception/NotFoundException.java
// public class NotFoundException extends Exception {
// public NotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/Category.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="priority_idx", columnList = "priority"),
// @Index(name="parentCategory_idx", columnList = "parent_category")})
// public class Category extends JPAEntity<Long> {
// private String name;
// private Integer priority;
// private Category parentCategory;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @NotNull
// @Column
// public Integer getPriority() {
// return priority;
// }
//
// public void setPriority(Integer priority) {
// this.priority = priority;
// }
//
// @ManyToOne(fetch = FetchType.EAGER)
// public Category getParentCategory() {
// return parentCategory;
// }
//
// public void setParentCategory(Category parentCategory) {
// this.parentCategory = parentCategory;
// }
//
// @Override
// public String toString() {
// return "Category{" +
// "name='" + name + '\'' +
// ", priority=" + priority +
// ", parentCategory=" + parentCategory +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/CategoryRepository.java
// public interface CategoryRepository extends BaseJPARepository<Category, Long> {
// /**
// * Finds a category with the given categoryName
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName);
//
// /**
// * Finds a category with the given categoryPriority
// *
// * @param categoryPriority
// * @return
// */
// public Category findByCategoryPriority(Integer categoryPriority);
//
// /**
// * Finds sub categories with the given parentCategory
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory);
// }
//
// Path: src/main/java/yourwebproject2/service/CategoryService.java
// public interface CategoryService extends BaseService<Category, Long> {
// /**
// * Validates whether the given category already
// * exists in the system.
// *
// * @param categoryName
// *
// * @return
// */
// public boolean isCategoryPresent(String categoryName);
//
// /**
// * Validates whether the given category priority already
// * exists in the system.
// *
// * @param priorityId
// *
// * @return
// */
// public boolean isPriorityPresent(Integer priorityId);
//
// /**
// * Find category by name
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName) throws NotFoundException;
//
// /**
// * Find sub categories by parent category
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory) throws NotFoundException;
// }
| import yourwebproject2.framework.data.BaseJPAServiceImpl;
import yourwebproject2.framework.exception.NotFoundException;
import yourwebproject2.model.entity.Category;
import yourwebproject2.model.repository.CategoryRepository;
import yourwebproject2.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.List; | package yourwebproject2.service.impl;
/**
* Created by Y.Kamesh on 8/2/2015.
*/
@Service
@Transactional | // Path: src/main/java/yourwebproject2/framework/data/BaseJPAServiceImpl.java
// public abstract class BaseJPAServiceImpl<T extends Entity, ID extends Serializable> implements BaseService<T, ID> {
// protected BaseJPARepository<T, ID> baseJpaRepository;
// protected Class<T> entityClass;
//
// public T insert(T object) throws Exception {
// return baseJpaRepository.insert(object);
// }
//
// public T update(T object) throws Exception {
// return baseJpaRepository.update(object);
// }
//
// public void delete(T object) throws Exception {
// baseJpaRepository.delete(object);
// }
//
// public T findById(ID id) throws Exception {
// T result = baseJpaRepository.findById(id);
//
// if (result != null)
// return result;
// else
// throw new Exception("Not Found");
// }
//
// public Collection<T> findAllByPage(int pageNum, int countPerPage, Order order) throws Exception {
// return null; //To change body of implemented methods use File | Settings | File Templates.
// }
// }
//
// Path: src/main/java/yourwebproject2/framework/exception/NotFoundException.java
// public class NotFoundException extends Exception {
// public NotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/Category.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="priority_idx", columnList = "priority"),
// @Index(name="parentCategory_idx", columnList = "parent_category")})
// public class Category extends JPAEntity<Long> {
// private String name;
// private Integer priority;
// private Category parentCategory;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @NotNull
// @Column
// public Integer getPriority() {
// return priority;
// }
//
// public void setPriority(Integer priority) {
// this.priority = priority;
// }
//
// @ManyToOne(fetch = FetchType.EAGER)
// public Category getParentCategory() {
// return parentCategory;
// }
//
// public void setParentCategory(Category parentCategory) {
// this.parentCategory = parentCategory;
// }
//
// @Override
// public String toString() {
// return "Category{" +
// "name='" + name + '\'' +
// ", priority=" + priority +
// ", parentCategory=" + parentCategory +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/CategoryRepository.java
// public interface CategoryRepository extends BaseJPARepository<Category, Long> {
// /**
// * Finds a category with the given categoryName
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName);
//
// /**
// * Finds a category with the given categoryPriority
// *
// * @param categoryPriority
// * @return
// */
// public Category findByCategoryPriority(Integer categoryPriority);
//
// /**
// * Finds sub categories with the given parentCategory
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory);
// }
//
// Path: src/main/java/yourwebproject2/service/CategoryService.java
// public interface CategoryService extends BaseService<Category, Long> {
// /**
// * Validates whether the given category already
// * exists in the system.
// *
// * @param categoryName
// *
// * @return
// */
// public boolean isCategoryPresent(String categoryName);
//
// /**
// * Validates whether the given category priority already
// * exists in the system.
// *
// * @param priorityId
// *
// * @return
// */
// public boolean isPriorityPresent(Integer priorityId);
//
// /**
// * Find category by name
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName) throws NotFoundException;
//
// /**
// * Find sub categories by parent category
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory) throws NotFoundException;
// }
// Path: src/main/java/yourwebproject2/service/impl/CategoryServiceImpl.java
import yourwebproject2.framework.data.BaseJPAServiceImpl;
import yourwebproject2.framework.exception.NotFoundException;
import yourwebproject2.model.entity.Category;
import yourwebproject2.model.repository.CategoryRepository;
import yourwebproject2.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.List;
package yourwebproject2.service.impl;
/**
* Created by Y.Kamesh on 8/2/2015.
*/
@Service
@Transactional | public class CategoryServiceImpl extends BaseJPAServiceImpl<Category, Long> implements CategoryService { |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/service/impl/CategoryServiceImpl.java | // Path: src/main/java/yourwebproject2/framework/data/BaseJPAServiceImpl.java
// public abstract class BaseJPAServiceImpl<T extends Entity, ID extends Serializable> implements BaseService<T, ID> {
// protected BaseJPARepository<T, ID> baseJpaRepository;
// protected Class<T> entityClass;
//
// public T insert(T object) throws Exception {
// return baseJpaRepository.insert(object);
// }
//
// public T update(T object) throws Exception {
// return baseJpaRepository.update(object);
// }
//
// public void delete(T object) throws Exception {
// baseJpaRepository.delete(object);
// }
//
// public T findById(ID id) throws Exception {
// T result = baseJpaRepository.findById(id);
//
// if (result != null)
// return result;
// else
// throw new Exception("Not Found");
// }
//
// public Collection<T> findAllByPage(int pageNum, int countPerPage, Order order) throws Exception {
// return null; //To change body of implemented methods use File | Settings | File Templates.
// }
// }
//
// Path: src/main/java/yourwebproject2/framework/exception/NotFoundException.java
// public class NotFoundException extends Exception {
// public NotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/Category.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="priority_idx", columnList = "priority"),
// @Index(name="parentCategory_idx", columnList = "parent_category")})
// public class Category extends JPAEntity<Long> {
// private String name;
// private Integer priority;
// private Category parentCategory;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @NotNull
// @Column
// public Integer getPriority() {
// return priority;
// }
//
// public void setPriority(Integer priority) {
// this.priority = priority;
// }
//
// @ManyToOne(fetch = FetchType.EAGER)
// public Category getParentCategory() {
// return parentCategory;
// }
//
// public void setParentCategory(Category parentCategory) {
// this.parentCategory = parentCategory;
// }
//
// @Override
// public String toString() {
// return "Category{" +
// "name='" + name + '\'' +
// ", priority=" + priority +
// ", parentCategory=" + parentCategory +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/CategoryRepository.java
// public interface CategoryRepository extends BaseJPARepository<Category, Long> {
// /**
// * Finds a category with the given categoryName
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName);
//
// /**
// * Finds a category with the given categoryPriority
// *
// * @param categoryPriority
// * @return
// */
// public Category findByCategoryPriority(Integer categoryPriority);
//
// /**
// * Finds sub categories with the given parentCategory
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory);
// }
//
// Path: src/main/java/yourwebproject2/service/CategoryService.java
// public interface CategoryService extends BaseService<Category, Long> {
// /**
// * Validates whether the given category already
// * exists in the system.
// *
// * @param categoryName
// *
// * @return
// */
// public boolean isCategoryPresent(String categoryName);
//
// /**
// * Validates whether the given category priority already
// * exists in the system.
// *
// * @param priorityId
// *
// * @return
// */
// public boolean isPriorityPresent(Integer priorityId);
//
// /**
// * Find category by name
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName) throws NotFoundException;
//
// /**
// * Find sub categories by parent category
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory) throws NotFoundException;
// }
| import yourwebproject2.framework.data.BaseJPAServiceImpl;
import yourwebproject2.framework.exception.NotFoundException;
import yourwebproject2.model.entity.Category;
import yourwebproject2.model.repository.CategoryRepository;
import yourwebproject2.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.List; | package yourwebproject2.service.impl;
/**
* Created by Y.Kamesh on 8/2/2015.
*/
@Service
@Transactional | // Path: src/main/java/yourwebproject2/framework/data/BaseJPAServiceImpl.java
// public abstract class BaseJPAServiceImpl<T extends Entity, ID extends Serializable> implements BaseService<T, ID> {
// protected BaseJPARepository<T, ID> baseJpaRepository;
// protected Class<T> entityClass;
//
// public T insert(T object) throws Exception {
// return baseJpaRepository.insert(object);
// }
//
// public T update(T object) throws Exception {
// return baseJpaRepository.update(object);
// }
//
// public void delete(T object) throws Exception {
// baseJpaRepository.delete(object);
// }
//
// public T findById(ID id) throws Exception {
// T result = baseJpaRepository.findById(id);
//
// if (result != null)
// return result;
// else
// throw new Exception("Not Found");
// }
//
// public Collection<T> findAllByPage(int pageNum, int countPerPage, Order order) throws Exception {
// return null; //To change body of implemented methods use File | Settings | File Templates.
// }
// }
//
// Path: src/main/java/yourwebproject2/framework/exception/NotFoundException.java
// public class NotFoundException extends Exception {
// public NotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/Category.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="priority_idx", columnList = "priority"),
// @Index(name="parentCategory_idx", columnList = "parent_category")})
// public class Category extends JPAEntity<Long> {
// private String name;
// private Integer priority;
// private Category parentCategory;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @NotNull
// @Column
// public Integer getPriority() {
// return priority;
// }
//
// public void setPriority(Integer priority) {
// this.priority = priority;
// }
//
// @ManyToOne(fetch = FetchType.EAGER)
// public Category getParentCategory() {
// return parentCategory;
// }
//
// public void setParentCategory(Category parentCategory) {
// this.parentCategory = parentCategory;
// }
//
// @Override
// public String toString() {
// return "Category{" +
// "name='" + name + '\'' +
// ", priority=" + priority +
// ", parentCategory=" + parentCategory +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/CategoryRepository.java
// public interface CategoryRepository extends BaseJPARepository<Category, Long> {
// /**
// * Finds a category with the given categoryName
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName);
//
// /**
// * Finds a category with the given categoryPriority
// *
// * @param categoryPriority
// * @return
// */
// public Category findByCategoryPriority(Integer categoryPriority);
//
// /**
// * Finds sub categories with the given parentCategory
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory);
// }
//
// Path: src/main/java/yourwebproject2/service/CategoryService.java
// public interface CategoryService extends BaseService<Category, Long> {
// /**
// * Validates whether the given category already
// * exists in the system.
// *
// * @param categoryName
// *
// * @return
// */
// public boolean isCategoryPresent(String categoryName);
//
// /**
// * Validates whether the given category priority already
// * exists in the system.
// *
// * @param priorityId
// *
// * @return
// */
// public boolean isPriorityPresent(Integer priorityId);
//
// /**
// * Find category by name
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName) throws NotFoundException;
//
// /**
// * Find sub categories by parent category
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory) throws NotFoundException;
// }
// Path: src/main/java/yourwebproject2/service/impl/CategoryServiceImpl.java
import yourwebproject2.framework.data.BaseJPAServiceImpl;
import yourwebproject2.framework.exception.NotFoundException;
import yourwebproject2.model.entity.Category;
import yourwebproject2.model.repository.CategoryRepository;
import yourwebproject2.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.List;
package yourwebproject2.service.impl;
/**
* Created by Y.Kamesh on 8/2/2015.
*/
@Service
@Transactional | public class CategoryServiceImpl extends BaseJPAServiceImpl<Category, Long> implements CategoryService { |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/service/impl/CategoryServiceImpl.java | // Path: src/main/java/yourwebproject2/framework/data/BaseJPAServiceImpl.java
// public abstract class BaseJPAServiceImpl<T extends Entity, ID extends Serializable> implements BaseService<T, ID> {
// protected BaseJPARepository<T, ID> baseJpaRepository;
// protected Class<T> entityClass;
//
// public T insert(T object) throws Exception {
// return baseJpaRepository.insert(object);
// }
//
// public T update(T object) throws Exception {
// return baseJpaRepository.update(object);
// }
//
// public void delete(T object) throws Exception {
// baseJpaRepository.delete(object);
// }
//
// public T findById(ID id) throws Exception {
// T result = baseJpaRepository.findById(id);
//
// if (result != null)
// return result;
// else
// throw new Exception("Not Found");
// }
//
// public Collection<T> findAllByPage(int pageNum, int countPerPage, Order order) throws Exception {
// return null; //To change body of implemented methods use File | Settings | File Templates.
// }
// }
//
// Path: src/main/java/yourwebproject2/framework/exception/NotFoundException.java
// public class NotFoundException extends Exception {
// public NotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/Category.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="priority_idx", columnList = "priority"),
// @Index(name="parentCategory_idx", columnList = "parent_category")})
// public class Category extends JPAEntity<Long> {
// private String name;
// private Integer priority;
// private Category parentCategory;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @NotNull
// @Column
// public Integer getPriority() {
// return priority;
// }
//
// public void setPriority(Integer priority) {
// this.priority = priority;
// }
//
// @ManyToOne(fetch = FetchType.EAGER)
// public Category getParentCategory() {
// return parentCategory;
// }
//
// public void setParentCategory(Category parentCategory) {
// this.parentCategory = parentCategory;
// }
//
// @Override
// public String toString() {
// return "Category{" +
// "name='" + name + '\'' +
// ", priority=" + priority +
// ", parentCategory=" + parentCategory +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/CategoryRepository.java
// public interface CategoryRepository extends BaseJPARepository<Category, Long> {
// /**
// * Finds a category with the given categoryName
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName);
//
// /**
// * Finds a category with the given categoryPriority
// *
// * @param categoryPriority
// * @return
// */
// public Category findByCategoryPriority(Integer categoryPriority);
//
// /**
// * Finds sub categories with the given parentCategory
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory);
// }
//
// Path: src/main/java/yourwebproject2/service/CategoryService.java
// public interface CategoryService extends BaseService<Category, Long> {
// /**
// * Validates whether the given category already
// * exists in the system.
// *
// * @param categoryName
// *
// * @return
// */
// public boolean isCategoryPresent(String categoryName);
//
// /**
// * Validates whether the given category priority already
// * exists in the system.
// *
// * @param priorityId
// *
// * @return
// */
// public boolean isPriorityPresent(Integer priorityId);
//
// /**
// * Find category by name
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName) throws NotFoundException;
//
// /**
// * Find sub categories by parent category
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory) throws NotFoundException;
// }
| import yourwebproject2.framework.data.BaseJPAServiceImpl;
import yourwebproject2.framework.exception.NotFoundException;
import yourwebproject2.model.entity.Category;
import yourwebproject2.model.repository.CategoryRepository;
import yourwebproject2.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.List; | package yourwebproject2.service.impl;
/**
* Created by Y.Kamesh on 8/2/2015.
*/
@Service
@Transactional
public class CategoryServiceImpl extends BaseJPAServiceImpl<Category, Long> implements CategoryService {
private static Logger LOG = LoggerFactory.getLogger(CategoryServiceImpl.class);
private @Autowired | // Path: src/main/java/yourwebproject2/framework/data/BaseJPAServiceImpl.java
// public abstract class BaseJPAServiceImpl<T extends Entity, ID extends Serializable> implements BaseService<T, ID> {
// protected BaseJPARepository<T, ID> baseJpaRepository;
// protected Class<T> entityClass;
//
// public T insert(T object) throws Exception {
// return baseJpaRepository.insert(object);
// }
//
// public T update(T object) throws Exception {
// return baseJpaRepository.update(object);
// }
//
// public void delete(T object) throws Exception {
// baseJpaRepository.delete(object);
// }
//
// public T findById(ID id) throws Exception {
// T result = baseJpaRepository.findById(id);
//
// if (result != null)
// return result;
// else
// throw new Exception("Not Found");
// }
//
// public Collection<T> findAllByPage(int pageNum, int countPerPage, Order order) throws Exception {
// return null; //To change body of implemented methods use File | Settings | File Templates.
// }
// }
//
// Path: src/main/java/yourwebproject2/framework/exception/NotFoundException.java
// public class NotFoundException extends Exception {
// public NotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/Category.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="priority_idx", columnList = "priority"),
// @Index(name="parentCategory_idx", columnList = "parent_category")})
// public class Category extends JPAEntity<Long> {
// private String name;
// private Integer priority;
// private Category parentCategory;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @NotNull
// @Column
// public Integer getPriority() {
// return priority;
// }
//
// public void setPriority(Integer priority) {
// this.priority = priority;
// }
//
// @ManyToOne(fetch = FetchType.EAGER)
// public Category getParentCategory() {
// return parentCategory;
// }
//
// public void setParentCategory(Category parentCategory) {
// this.parentCategory = parentCategory;
// }
//
// @Override
// public String toString() {
// return "Category{" +
// "name='" + name + '\'' +
// ", priority=" + priority +
// ", parentCategory=" + parentCategory +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/CategoryRepository.java
// public interface CategoryRepository extends BaseJPARepository<Category, Long> {
// /**
// * Finds a category with the given categoryName
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName);
//
// /**
// * Finds a category with the given categoryPriority
// *
// * @param categoryPriority
// * @return
// */
// public Category findByCategoryPriority(Integer categoryPriority);
//
// /**
// * Finds sub categories with the given parentCategory
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory);
// }
//
// Path: src/main/java/yourwebproject2/service/CategoryService.java
// public interface CategoryService extends BaseService<Category, Long> {
// /**
// * Validates whether the given category already
// * exists in the system.
// *
// * @param categoryName
// *
// * @return
// */
// public boolean isCategoryPresent(String categoryName);
//
// /**
// * Validates whether the given category priority already
// * exists in the system.
// *
// * @param priorityId
// *
// * @return
// */
// public boolean isPriorityPresent(Integer priorityId);
//
// /**
// * Find category by name
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName) throws NotFoundException;
//
// /**
// * Find sub categories by parent category
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory) throws NotFoundException;
// }
// Path: src/main/java/yourwebproject2/service/impl/CategoryServiceImpl.java
import yourwebproject2.framework.data.BaseJPAServiceImpl;
import yourwebproject2.framework.exception.NotFoundException;
import yourwebproject2.model.entity.Category;
import yourwebproject2.model.repository.CategoryRepository;
import yourwebproject2.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.List;
package yourwebproject2.service.impl;
/**
* Created by Y.Kamesh on 8/2/2015.
*/
@Service
@Transactional
public class CategoryServiceImpl extends BaseJPAServiceImpl<Category, Long> implements CategoryService {
private static Logger LOG = LoggerFactory.getLogger(CategoryServiceImpl.class);
private @Autowired | CategoryRepository categoryRepository; |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/service/impl/CategoryServiceImpl.java | // Path: src/main/java/yourwebproject2/framework/data/BaseJPAServiceImpl.java
// public abstract class BaseJPAServiceImpl<T extends Entity, ID extends Serializable> implements BaseService<T, ID> {
// protected BaseJPARepository<T, ID> baseJpaRepository;
// protected Class<T> entityClass;
//
// public T insert(T object) throws Exception {
// return baseJpaRepository.insert(object);
// }
//
// public T update(T object) throws Exception {
// return baseJpaRepository.update(object);
// }
//
// public void delete(T object) throws Exception {
// baseJpaRepository.delete(object);
// }
//
// public T findById(ID id) throws Exception {
// T result = baseJpaRepository.findById(id);
//
// if (result != null)
// return result;
// else
// throw new Exception("Not Found");
// }
//
// public Collection<T> findAllByPage(int pageNum, int countPerPage, Order order) throws Exception {
// return null; //To change body of implemented methods use File | Settings | File Templates.
// }
// }
//
// Path: src/main/java/yourwebproject2/framework/exception/NotFoundException.java
// public class NotFoundException extends Exception {
// public NotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/Category.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="priority_idx", columnList = "priority"),
// @Index(name="parentCategory_idx", columnList = "parent_category")})
// public class Category extends JPAEntity<Long> {
// private String name;
// private Integer priority;
// private Category parentCategory;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @NotNull
// @Column
// public Integer getPriority() {
// return priority;
// }
//
// public void setPriority(Integer priority) {
// this.priority = priority;
// }
//
// @ManyToOne(fetch = FetchType.EAGER)
// public Category getParentCategory() {
// return parentCategory;
// }
//
// public void setParentCategory(Category parentCategory) {
// this.parentCategory = parentCategory;
// }
//
// @Override
// public String toString() {
// return "Category{" +
// "name='" + name + '\'' +
// ", priority=" + priority +
// ", parentCategory=" + parentCategory +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/CategoryRepository.java
// public interface CategoryRepository extends BaseJPARepository<Category, Long> {
// /**
// * Finds a category with the given categoryName
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName);
//
// /**
// * Finds a category with the given categoryPriority
// *
// * @param categoryPriority
// * @return
// */
// public Category findByCategoryPriority(Integer categoryPriority);
//
// /**
// * Finds sub categories with the given parentCategory
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory);
// }
//
// Path: src/main/java/yourwebproject2/service/CategoryService.java
// public interface CategoryService extends BaseService<Category, Long> {
// /**
// * Validates whether the given category already
// * exists in the system.
// *
// * @param categoryName
// *
// * @return
// */
// public boolean isCategoryPresent(String categoryName);
//
// /**
// * Validates whether the given category priority already
// * exists in the system.
// *
// * @param priorityId
// *
// * @return
// */
// public boolean isPriorityPresent(Integer priorityId);
//
// /**
// * Find category by name
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName) throws NotFoundException;
//
// /**
// * Find sub categories by parent category
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory) throws NotFoundException;
// }
| import yourwebproject2.framework.data.BaseJPAServiceImpl;
import yourwebproject2.framework.exception.NotFoundException;
import yourwebproject2.model.entity.Category;
import yourwebproject2.model.repository.CategoryRepository;
import yourwebproject2.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.List; | package yourwebproject2.service.impl;
/**
* Created by Y.Kamesh on 8/2/2015.
*/
@Service
@Transactional
public class CategoryServiceImpl extends BaseJPAServiceImpl<Category, Long> implements CategoryService {
private static Logger LOG = LoggerFactory.getLogger(CategoryServiceImpl.class);
private @Autowired
CategoryRepository categoryRepository;
@PostConstruct
public void setupService() {
LOG.info("setting up categoryService...");
this.baseJpaRepository = categoryRepository;
this.entityClass = Category.class;
this.baseJpaRepository.setupEntityClass(Category.class);
LOG.info("categoryService created...");
}
@Override
public boolean isCategoryPresent(String categoryName) {
if (categoryRepository.findByCategoryName(categoryName) != null) {
return true;
} else
return false;
}
@Override
public boolean isPriorityPresent(Integer categoryPriority) {
if (categoryRepository.findByCategoryPriority(categoryPriority) != null) {
return true;
} else
return false;
}
@Override | // Path: src/main/java/yourwebproject2/framework/data/BaseJPAServiceImpl.java
// public abstract class BaseJPAServiceImpl<T extends Entity, ID extends Serializable> implements BaseService<T, ID> {
// protected BaseJPARepository<T, ID> baseJpaRepository;
// protected Class<T> entityClass;
//
// public T insert(T object) throws Exception {
// return baseJpaRepository.insert(object);
// }
//
// public T update(T object) throws Exception {
// return baseJpaRepository.update(object);
// }
//
// public void delete(T object) throws Exception {
// baseJpaRepository.delete(object);
// }
//
// public T findById(ID id) throws Exception {
// T result = baseJpaRepository.findById(id);
//
// if (result != null)
// return result;
// else
// throw new Exception("Not Found");
// }
//
// public Collection<T> findAllByPage(int pageNum, int countPerPage, Order order) throws Exception {
// return null; //To change body of implemented methods use File | Settings | File Templates.
// }
// }
//
// Path: src/main/java/yourwebproject2/framework/exception/NotFoundException.java
// public class NotFoundException extends Exception {
// public NotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/Category.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="priority_idx", columnList = "priority"),
// @Index(name="parentCategory_idx", columnList = "parent_category")})
// public class Category extends JPAEntity<Long> {
// private String name;
// private Integer priority;
// private Category parentCategory;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @NotNull
// @Column
// public Integer getPriority() {
// return priority;
// }
//
// public void setPriority(Integer priority) {
// this.priority = priority;
// }
//
// @ManyToOne(fetch = FetchType.EAGER)
// public Category getParentCategory() {
// return parentCategory;
// }
//
// public void setParentCategory(Category parentCategory) {
// this.parentCategory = parentCategory;
// }
//
// @Override
// public String toString() {
// return "Category{" +
// "name='" + name + '\'' +
// ", priority=" + priority +
// ", parentCategory=" + parentCategory +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/CategoryRepository.java
// public interface CategoryRepository extends BaseJPARepository<Category, Long> {
// /**
// * Finds a category with the given categoryName
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName);
//
// /**
// * Finds a category with the given categoryPriority
// *
// * @param categoryPriority
// * @return
// */
// public Category findByCategoryPriority(Integer categoryPriority);
//
// /**
// * Finds sub categories with the given parentCategory
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory);
// }
//
// Path: src/main/java/yourwebproject2/service/CategoryService.java
// public interface CategoryService extends BaseService<Category, Long> {
// /**
// * Validates whether the given category already
// * exists in the system.
// *
// * @param categoryName
// *
// * @return
// */
// public boolean isCategoryPresent(String categoryName);
//
// /**
// * Validates whether the given category priority already
// * exists in the system.
// *
// * @param priorityId
// *
// * @return
// */
// public boolean isPriorityPresent(Integer priorityId);
//
// /**
// * Find category by name
// *
// * @param categoryName
// * @return
// */
// public Category findByCategoryName(String categoryName) throws NotFoundException;
//
// /**
// * Find sub categories by parent category
// *
// * @param parentCategory
// * @return
// */
// public List<Category> findSubCategories(Category parentCategory) throws NotFoundException;
// }
// Path: src/main/java/yourwebproject2/service/impl/CategoryServiceImpl.java
import yourwebproject2.framework.data.BaseJPAServiceImpl;
import yourwebproject2.framework.exception.NotFoundException;
import yourwebproject2.model.entity.Category;
import yourwebproject2.model.repository.CategoryRepository;
import yourwebproject2.service.CategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.List;
package yourwebproject2.service.impl;
/**
* Created by Y.Kamesh on 8/2/2015.
*/
@Service
@Transactional
public class CategoryServiceImpl extends BaseJPAServiceImpl<Category, Long> implements CategoryService {
private static Logger LOG = LoggerFactory.getLogger(CategoryServiceImpl.class);
private @Autowired
CategoryRepository categoryRepository;
@PostConstruct
public void setupService() {
LOG.info("setting up categoryService...");
this.baseJpaRepository = categoryRepository;
this.entityClass = Category.class;
this.baseJpaRepository.setupEntityClass(Category.class);
LOG.info("categoryService created...");
}
@Override
public boolean isCategoryPresent(String categoryName) {
if (categoryRepository.findByCategoryName(categoryName) != null) {
return true;
} else
return false;
}
@Override
public boolean isPriorityPresent(Integer categoryPriority) {
if (categoryRepository.findByCategoryPriority(categoryPriority) != null) {
return true;
} else
return false;
}
@Override | public Category findByCategoryName(String categoryName) throws NotFoundException { |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/controller/ErrorController.java | // Path: src/main/java/yourwebproject2/framework/api/APIResponse.java
// @JsonInclude(JsonInclude.Include.NON_NULL)
// public class APIResponse {
// public static final String API_RESPONSE = "apiResponse";
// Object result;
// String time;
// long code;
//
// public static class ExceptionAPIResponse extends APIResponse {
// Object details;
//
// public Object getDetails() {
// return details;
// }
//
// public void setDetails(Object details) {
// this.details = details;
// }
// }
//
// public Object getResult() {
// return result;
// }
//
// public void setResult(Object result) {
// this.result = result;
// }
//
// public String getTime() {
// return time;
// }
//
// public void setTime(String time) {
// this.time = time;
// }
//
// public long getCode() {
// return code;
// }
//
// public void setCode(long code) {
// this.code = code;
// }
//
// public static APIResponse toOkResponse(Object data) {
// return toAPIResponse(data, 200);
// }
//
// public static APIResponse toErrorResponse(Object data) {
// return toAPIResponse(data, 2001);
// }
//
// public static ExceptionAPIResponse toExceptionResponse(String result, Object details) {
// ExceptionAPIResponse response = new ExceptionAPIResponse();
// response.setResult(result);
// response.setDetails(details);
// response.setCode(2001);
// return response;
// }
//
// public APIResponse withModelAndView(ModelAndView modelAndView) {
// modelAndView.addObject(API_RESPONSE, this);
// return this;
// }
//
// public static APIResponse toAPIResponse(Object data, long code) {
// APIResponse response = new APIResponse();
// response.setResult(data);
// response.setCode(code);
// return response;
// }
// }
//
// Path: src/main/java/yourwebproject2/framework/controller/BaseController.java
// public abstract class BaseController {
// protected static final String JSON_API_CONTENT_HEADER = "Content-type=application/json";
//
// public String extractPostRequestBody(HttpServletRequest request) throws IOException {
// if ("POST".equalsIgnoreCase(request.getMethod())) {
// Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
// return s.hasNext() ? s.next() : "";
// }
// return "";
// }
//
// public JSONObject parseJSON(String object) {
// return new JSONObject(object);
// }
//
// public void decorateUserDTOWithCredsFromAuthHeader(String authHeader, UserDTO userDTO) {
// String[] basicAuth = authHeader.split(" ");
// Validate.isTrue(basicAuth.length == 2, "the auth header is not splittable with space");
// Validate.isTrue(basicAuth[0].equalsIgnoreCase("basic"), "not basic auth: "+basicAuth[0]);
// Validate.isTrue(Base64.isBase64(basicAuth[1].getBytes()), "encoded value not base64");
//
// String decodedAuthHeader = new String(Base64.decode(basicAuth[1].getBytes()));
// String[] creds = decodedAuthHeader.split(":");
// Validate.isTrue(creds.length == 2, "the creds were not concatenated using ':', could not split the decoded header");
//
// userDTO.setEmail(creds[0]);
// userDTO.setPassword(creds[1]);
// }
// }
| import yourwebproject2.framework.api.APIResponse;
import yourwebproject2.framework.controller.BaseController;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map; | package yourwebproject2.controller;
/**
* @author: kameshr
*/
@Controller
public class ErrorController extends BaseController {
private static Logger LOG = LoggerFactory.getLogger(ErrorController.class);
@RequestMapping("error") | // Path: src/main/java/yourwebproject2/framework/api/APIResponse.java
// @JsonInclude(JsonInclude.Include.NON_NULL)
// public class APIResponse {
// public static final String API_RESPONSE = "apiResponse";
// Object result;
// String time;
// long code;
//
// public static class ExceptionAPIResponse extends APIResponse {
// Object details;
//
// public Object getDetails() {
// return details;
// }
//
// public void setDetails(Object details) {
// this.details = details;
// }
// }
//
// public Object getResult() {
// return result;
// }
//
// public void setResult(Object result) {
// this.result = result;
// }
//
// public String getTime() {
// return time;
// }
//
// public void setTime(String time) {
// this.time = time;
// }
//
// public long getCode() {
// return code;
// }
//
// public void setCode(long code) {
// this.code = code;
// }
//
// public static APIResponse toOkResponse(Object data) {
// return toAPIResponse(data, 200);
// }
//
// public static APIResponse toErrorResponse(Object data) {
// return toAPIResponse(data, 2001);
// }
//
// public static ExceptionAPIResponse toExceptionResponse(String result, Object details) {
// ExceptionAPIResponse response = new ExceptionAPIResponse();
// response.setResult(result);
// response.setDetails(details);
// response.setCode(2001);
// return response;
// }
//
// public APIResponse withModelAndView(ModelAndView modelAndView) {
// modelAndView.addObject(API_RESPONSE, this);
// return this;
// }
//
// public static APIResponse toAPIResponse(Object data, long code) {
// APIResponse response = new APIResponse();
// response.setResult(data);
// response.setCode(code);
// return response;
// }
// }
//
// Path: src/main/java/yourwebproject2/framework/controller/BaseController.java
// public abstract class BaseController {
// protected static final String JSON_API_CONTENT_HEADER = "Content-type=application/json";
//
// public String extractPostRequestBody(HttpServletRequest request) throws IOException {
// if ("POST".equalsIgnoreCase(request.getMethod())) {
// Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
// return s.hasNext() ? s.next() : "";
// }
// return "";
// }
//
// public JSONObject parseJSON(String object) {
// return new JSONObject(object);
// }
//
// public void decorateUserDTOWithCredsFromAuthHeader(String authHeader, UserDTO userDTO) {
// String[] basicAuth = authHeader.split(" ");
// Validate.isTrue(basicAuth.length == 2, "the auth header is not splittable with space");
// Validate.isTrue(basicAuth[0].equalsIgnoreCase("basic"), "not basic auth: "+basicAuth[0]);
// Validate.isTrue(Base64.isBase64(basicAuth[1].getBytes()), "encoded value not base64");
//
// String decodedAuthHeader = new String(Base64.decode(basicAuth[1].getBytes()));
// String[] creds = decodedAuthHeader.split(":");
// Validate.isTrue(creds.length == 2, "the creds were not concatenated using ':', could not split the decoded header");
//
// userDTO.setEmail(creds[0]);
// userDTO.setPassword(creds[1]);
// }
// }
// Path: src/main/java/yourwebproject2/controller/ErrorController.java
import yourwebproject2.framework.api.APIResponse;
import yourwebproject2.framework.controller.BaseController;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
package yourwebproject2.controller;
/**
* @author: kameshr
*/
@Controller
public class ErrorController extends BaseController {
private static Logger LOG = LoggerFactory.getLogger(ErrorController.class);
@RequestMapping("error") | public @ResponseBody APIResponse customError(HttpServletRequest request, HttpServletResponse response) { |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/model/entity/Job.java | // Path: src/main/java/yourwebproject2/framework/data/JPAEntity.java
// @MappedSuperclass
// public abstract class JPAEntity<T extends Serializable> implements Entity {
// protected T id;
// protected Date createdAt;
// protected Date updatedAt;
//
//
// public JPAEntity() {
// createdAt = new Date();
// updatedAt = new Date();
// }
//
//
// /**
// * To make XStream deserialization assign values to
// * base class fields of createdAt and updatedAt
// *
// * @return
// */
// public Object readResolve() {
// if (this.createdAt == null) {
// this.createdAt = new Date();
// this.updatedAt = createdAt;
// }
//
// return this;
// }
//
//
// @XmlElement(type = Object.class) @Id @GeneratedValue
// public T getId() {
// return id;
// }
//
//
// public void setId(T id) {
// this.id = id;
// }
//
//
// @JsonIgnore @Temporal(TemporalType.DATE) @Column
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public void setCreatedAt(Date createdAt) {
// this.createdAt = createdAt;
// }
//
//
// @JsonIgnore @Temporal(TemporalType.TIMESTAMP) @Column
// public Date getUpdatedAt() {
// return updatedAt;
// }
//
//
// public void setUpdatedAt(Date updatedAt) {
// this.updatedAt = updatedAt;
// }
// }
| import yourwebproject2.framework.data.JPAEntity;
import org.hibernate.validator.constraints.NotBlank;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date; | package yourwebproject2.model.entity;
/**
* The core Job Entity
*
* Created by Y.Kamesh on 8/2/2015.
*/
@Entity
@Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
@Index(name="status_idx", columnList = "status"),
@Index(name="category_idx", columnList = "category")}) | // Path: src/main/java/yourwebproject2/framework/data/JPAEntity.java
// @MappedSuperclass
// public abstract class JPAEntity<T extends Serializable> implements Entity {
// protected T id;
// protected Date createdAt;
// protected Date updatedAt;
//
//
// public JPAEntity() {
// createdAt = new Date();
// updatedAt = new Date();
// }
//
//
// /**
// * To make XStream deserialization assign values to
// * base class fields of createdAt and updatedAt
// *
// * @return
// */
// public Object readResolve() {
// if (this.createdAt == null) {
// this.createdAt = new Date();
// this.updatedAt = createdAt;
// }
//
// return this;
// }
//
//
// @XmlElement(type = Object.class) @Id @GeneratedValue
// public T getId() {
// return id;
// }
//
//
// public void setId(T id) {
// this.id = id;
// }
//
//
// @JsonIgnore @Temporal(TemporalType.DATE) @Column
// public Date getCreatedAt() {
// return createdAt;
// }
//
//
// public void setCreatedAt(Date createdAt) {
// this.createdAt = createdAt;
// }
//
//
// @JsonIgnore @Temporal(TemporalType.TIMESTAMP) @Column
// public Date getUpdatedAt() {
// return updatedAt;
// }
//
//
// public void setUpdatedAt(Date updatedAt) {
// this.updatedAt = updatedAt;
// }
// }
// Path: src/main/java/yourwebproject2/model/entity/Job.java
import yourwebproject2.framework.data.JPAEntity;
import org.hibernate.validator.constraints.NotBlank;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
package yourwebproject2.model.entity;
/**
* The core Job Entity
*
* Created by Y.Kamesh on 8/2/2015.
*/
@Entity
@Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
@Index(name="status_idx", columnList = "status"),
@Index(name="category_idx", columnList = "category")}) | public class Job extends JPAEntity<Long> { |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/unusedspringsecurity/UserDetailsServiceImpl.java | // Path: src/main/java/yourwebproject2/framework/exception/EmailNotFoundException.java
// public class EmailNotFoundException extends AuthenticationException {
// public EmailNotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/User.java
// @Entity
// @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
// @Table(indexes = { @Index(name="email_idx", columnList = "email", unique = true),
// @Index(name="displayName_idx", columnList = "display_name") })
// public class User extends JPAEntity<Long> implements Serializable {
// public enum Role {
// USER,
// ADMIN
// }
//
// private String email;
// private @JsonIgnore String password;
// private boolean enabled;
// private Role role;
// private String displayName;
//
// private @JsonIgnore Integer loginCount;
// private Date currentLoginAt;
// private Date lastLoginAt;
// private @JsonIgnore String currentLoginIp;
// private @JsonIgnore String lastLoginIp;
//
// private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//
// @Column @Email @NotNull @NotBlank
// public String getEmail() {
// return this.email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// @JsonIgnore @Column(nullable = false, length = 60)
// public String getPassword() {
// return this.password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Column(nullable = false)
// public boolean isEnabled() {
// return this.enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// @Column(nullable = false)
// public Role getRole() {
// return this.role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// @Column(name="display_name")
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// @JsonIgnore @Column
// public Integer getLoginCount() {
// return loginCount;
// }
//
// public void setLoginCount(Integer loginCount) {
// this.loginCount = loginCount;
// }
//
// @Column
// public Date getCurrentLoginAt() {
// return currentLoginAt;
// }
//
// public void setCurrentLoginAt(Date currentLoginAt) {
// this.currentLoginAt = currentLoginAt;
// }
//
// @Column
// public Date getLastLoginAt() {
// return lastLoginAt;
// }
//
// public void setLastLoginAt(Date lastLoginAt) {
// this.lastLoginAt = lastLoginAt;
// }
//
// @JsonIgnore @Column
// public String getCurrentLoginIp() {
// return currentLoginIp;
// }
//
// public void setCurrentLoginIp(String currentLoginIp) {
// this.currentLoginIp = currentLoginIp;
// }
//
// @JsonIgnore @Column
// public String getLastLoginIp() {
// return lastLoginIp;
// }
//
// public void setLastLoginIp(String lastLoginIp) {
// this.lastLoginIp = lastLoginIp;
// }
//
// /**
// * Method to create the hash of the password before storing
// *
// * @param pass
// *
// * @return SHA hash digest of the password
// */
// public static synchronized String hashPassword(String pass) {
// return passwordEncoder.encode(pass);
// }
//
// public static synchronized boolean doesPasswordMatch(String rawPass, String encodedPass) {
// return passwordEncoder.matches(rawPass, encodedPass);
// }
//
// @Override
// public String toString() {
// return "User{" +
// "email='" + email + '\'' +
// ", password='" + password + '\'' +
// ", enabled=" + enabled +
// ", role=" + role +
// ", displayName='" + displayName + '\'' +
// ", loginCount=" + loginCount +
// ", currentLoginAt=" + currentLoginAt +
// ", lastLoginAt=" + lastLoginAt +
// ", currentLoginIp='" + currentLoginIp + '\'' +
// ", lastLoginIp='" + lastLoginIp + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/UserRepository.java
// public interface UserRepository extends BaseJPARepository<User, Long> {
// /**
// * Finds a user with the given email
// *
// * @param email
// * @return
// */
// public User findByEmail(String email);
// }
| import yourwebproject2.framework.exception.EmailNotFoundException;
import yourwebproject2.model.entity.User;
import yourwebproject2.model.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*; | package yourwebproject2.unusedspringsecurity;
/**
* @author: kameshr
*/
@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService { | // Path: src/main/java/yourwebproject2/framework/exception/EmailNotFoundException.java
// public class EmailNotFoundException extends AuthenticationException {
// public EmailNotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/User.java
// @Entity
// @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
// @Table(indexes = { @Index(name="email_idx", columnList = "email", unique = true),
// @Index(name="displayName_idx", columnList = "display_name") })
// public class User extends JPAEntity<Long> implements Serializable {
// public enum Role {
// USER,
// ADMIN
// }
//
// private String email;
// private @JsonIgnore String password;
// private boolean enabled;
// private Role role;
// private String displayName;
//
// private @JsonIgnore Integer loginCount;
// private Date currentLoginAt;
// private Date lastLoginAt;
// private @JsonIgnore String currentLoginIp;
// private @JsonIgnore String lastLoginIp;
//
// private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//
// @Column @Email @NotNull @NotBlank
// public String getEmail() {
// return this.email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// @JsonIgnore @Column(nullable = false, length = 60)
// public String getPassword() {
// return this.password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Column(nullable = false)
// public boolean isEnabled() {
// return this.enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// @Column(nullable = false)
// public Role getRole() {
// return this.role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// @Column(name="display_name")
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// @JsonIgnore @Column
// public Integer getLoginCount() {
// return loginCount;
// }
//
// public void setLoginCount(Integer loginCount) {
// this.loginCount = loginCount;
// }
//
// @Column
// public Date getCurrentLoginAt() {
// return currentLoginAt;
// }
//
// public void setCurrentLoginAt(Date currentLoginAt) {
// this.currentLoginAt = currentLoginAt;
// }
//
// @Column
// public Date getLastLoginAt() {
// return lastLoginAt;
// }
//
// public void setLastLoginAt(Date lastLoginAt) {
// this.lastLoginAt = lastLoginAt;
// }
//
// @JsonIgnore @Column
// public String getCurrentLoginIp() {
// return currentLoginIp;
// }
//
// public void setCurrentLoginIp(String currentLoginIp) {
// this.currentLoginIp = currentLoginIp;
// }
//
// @JsonIgnore @Column
// public String getLastLoginIp() {
// return lastLoginIp;
// }
//
// public void setLastLoginIp(String lastLoginIp) {
// this.lastLoginIp = lastLoginIp;
// }
//
// /**
// * Method to create the hash of the password before storing
// *
// * @param pass
// *
// * @return SHA hash digest of the password
// */
// public static synchronized String hashPassword(String pass) {
// return passwordEncoder.encode(pass);
// }
//
// public static synchronized boolean doesPasswordMatch(String rawPass, String encodedPass) {
// return passwordEncoder.matches(rawPass, encodedPass);
// }
//
// @Override
// public String toString() {
// return "User{" +
// "email='" + email + '\'' +
// ", password='" + password + '\'' +
// ", enabled=" + enabled +
// ", role=" + role +
// ", displayName='" + displayName + '\'' +
// ", loginCount=" + loginCount +
// ", currentLoginAt=" + currentLoginAt +
// ", lastLoginAt=" + lastLoginAt +
// ", currentLoginIp='" + currentLoginIp + '\'' +
// ", lastLoginIp='" + lastLoginIp + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/UserRepository.java
// public interface UserRepository extends BaseJPARepository<User, Long> {
// /**
// * Finds a user with the given email
// *
// * @param email
// * @return
// */
// public User findByEmail(String email);
// }
// Path: src/main/java/yourwebproject2/unusedspringsecurity/UserDetailsServiceImpl.java
import yourwebproject2.framework.exception.EmailNotFoundException;
import yourwebproject2.model.entity.User;
import yourwebproject2.model.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
package yourwebproject2.unusedspringsecurity;
/**
* @author: kameshr
*/
@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService { | private @Autowired UserRepository userRepository; |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/unusedspringsecurity/UserDetailsServiceImpl.java | // Path: src/main/java/yourwebproject2/framework/exception/EmailNotFoundException.java
// public class EmailNotFoundException extends AuthenticationException {
// public EmailNotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/User.java
// @Entity
// @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
// @Table(indexes = { @Index(name="email_idx", columnList = "email", unique = true),
// @Index(name="displayName_idx", columnList = "display_name") })
// public class User extends JPAEntity<Long> implements Serializable {
// public enum Role {
// USER,
// ADMIN
// }
//
// private String email;
// private @JsonIgnore String password;
// private boolean enabled;
// private Role role;
// private String displayName;
//
// private @JsonIgnore Integer loginCount;
// private Date currentLoginAt;
// private Date lastLoginAt;
// private @JsonIgnore String currentLoginIp;
// private @JsonIgnore String lastLoginIp;
//
// private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//
// @Column @Email @NotNull @NotBlank
// public String getEmail() {
// return this.email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// @JsonIgnore @Column(nullable = false, length = 60)
// public String getPassword() {
// return this.password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Column(nullable = false)
// public boolean isEnabled() {
// return this.enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// @Column(nullable = false)
// public Role getRole() {
// return this.role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// @Column(name="display_name")
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// @JsonIgnore @Column
// public Integer getLoginCount() {
// return loginCount;
// }
//
// public void setLoginCount(Integer loginCount) {
// this.loginCount = loginCount;
// }
//
// @Column
// public Date getCurrentLoginAt() {
// return currentLoginAt;
// }
//
// public void setCurrentLoginAt(Date currentLoginAt) {
// this.currentLoginAt = currentLoginAt;
// }
//
// @Column
// public Date getLastLoginAt() {
// return lastLoginAt;
// }
//
// public void setLastLoginAt(Date lastLoginAt) {
// this.lastLoginAt = lastLoginAt;
// }
//
// @JsonIgnore @Column
// public String getCurrentLoginIp() {
// return currentLoginIp;
// }
//
// public void setCurrentLoginIp(String currentLoginIp) {
// this.currentLoginIp = currentLoginIp;
// }
//
// @JsonIgnore @Column
// public String getLastLoginIp() {
// return lastLoginIp;
// }
//
// public void setLastLoginIp(String lastLoginIp) {
// this.lastLoginIp = lastLoginIp;
// }
//
// /**
// * Method to create the hash of the password before storing
// *
// * @param pass
// *
// * @return SHA hash digest of the password
// */
// public static synchronized String hashPassword(String pass) {
// return passwordEncoder.encode(pass);
// }
//
// public static synchronized boolean doesPasswordMatch(String rawPass, String encodedPass) {
// return passwordEncoder.matches(rawPass, encodedPass);
// }
//
// @Override
// public String toString() {
// return "User{" +
// "email='" + email + '\'' +
// ", password='" + password + '\'' +
// ", enabled=" + enabled +
// ", role=" + role +
// ", displayName='" + displayName + '\'' +
// ", loginCount=" + loginCount +
// ", currentLoginAt=" + currentLoginAt +
// ", lastLoginAt=" + lastLoginAt +
// ", currentLoginIp='" + currentLoginIp + '\'' +
// ", lastLoginIp='" + lastLoginIp + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/UserRepository.java
// public interface UserRepository extends BaseJPARepository<User, Long> {
// /**
// * Finds a user with the given email
// *
// * @param email
// * @return
// */
// public User findByEmail(String email);
// }
| import yourwebproject2.framework.exception.EmailNotFoundException;
import yourwebproject2.model.entity.User;
import yourwebproject2.model.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*; | package yourwebproject2.unusedspringsecurity;
/**
* @author: kameshr
*/
@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {
private @Autowired UserRepository userRepository;
@Override
@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return loadUserByEmail(username);
}
private UserDetails loadUserByEmail(final String email) | // Path: src/main/java/yourwebproject2/framework/exception/EmailNotFoundException.java
// public class EmailNotFoundException extends AuthenticationException {
// public EmailNotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/User.java
// @Entity
// @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
// @Table(indexes = { @Index(name="email_idx", columnList = "email", unique = true),
// @Index(name="displayName_idx", columnList = "display_name") })
// public class User extends JPAEntity<Long> implements Serializable {
// public enum Role {
// USER,
// ADMIN
// }
//
// private String email;
// private @JsonIgnore String password;
// private boolean enabled;
// private Role role;
// private String displayName;
//
// private @JsonIgnore Integer loginCount;
// private Date currentLoginAt;
// private Date lastLoginAt;
// private @JsonIgnore String currentLoginIp;
// private @JsonIgnore String lastLoginIp;
//
// private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//
// @Column @Email @NotNull @NotBlank
// public String getEmail() {
// return this.email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// @JsonIgnore @Column(nullable = false, length = 60)
// public String getPassword() {
// return this.password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Column(nullable = false)
// public boolean isEnabled() {
// return this.enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// @Column(nullable = false)
// public Role getRole() {
// return this.role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// @Column(name="display_name")
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// @JsonIgnore @Column
// public Integer getLoginCount() {
// return loginCount;
// }
//
// public void setLoginCount(Integer loginCount) {
// this.loginCount = loginCount;
// }
//
// @Column
// public Date getCurrentLoginAt() {
// return currentLoginAt;
// }
//
// public void setCurrentLoginAt(Date currentLoginAt) {
// this.currentLoginAt = currentLoginAt;
// }
//
// @Column
// public Date getLastLoginAt() {
// return lastLoginAt;
// }
//
// public void setLastLoginAt(Date lastLoginAt) {
// this.lastLoginAt = lastLoginAt;
// }
//
// @JsonIgnore @Column
// public String getCurrentLoginIp() {
// return currentLoginIp;
// }
//
// public void setCurrentLoginIp(String currentLoginIp) {
// this.currentLoginIp = currentLoginIp;
// }
//
// @JsonIgnore @Column
// public String getLastLoginIp() {
// return lastLoginIp;
// }
//
// public void setLastLoginIp(String lastLoginIp) {
// this.lastLoginIp = lastLoginIp;
// }
//
// /**
// * Method to create the hash of the password before storing
// *
// * @param pass
// *
// * @return SHA hash digest of the password
// */
// public static synchronized String hashPassword(String pass) {
// return passwordEncoder.encode(pass);
// }
//
// public static synchronized boolean doesPasswordMatch(String rawPass, String encodedPass) {
// return passwordEncoder.matches(rawPass, encodedPass);
// }
//
// @Override
// public String toString() {
// return "User{" +
// "email='" + email + '\'' +
// ", password='" + password + '\'' +
// ", enabled=" + enabled +
// ", role=" + role +
// ", displayName='" + displayName + '\'' +
// ", loginCount=" + loginCount +
// ", currentLoginAt=" + currentLoginAt +
// ", lastLoginAt=" + lastLoginAt +
// ", currentLoginIp='" + currentLoginIp + '\'' +
// ", lastLoginIp='" + lastLoginIp + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/UserRepository.java
// public interface UserRepository extends BaseJPARepository<User, Long> {
// /**
// * Finds a user with the given email
// *
// * @param email
// * @return
// */
// public User findByEmail(String email);
// }
// Path: src/main/java/yourwebproject2/unusedspringsecurity/UserDetailsServiceImpl.java
import yourwebproject2.framework.exception.EmailNotFoundException;
import yourwebproject2.model.entity.User;
import yourwebproject2.model.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
package yourwebproject2.unusedspringsecurity;
/**
* @author: kameshr
*/
@Service
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService {
private @Autowired UserRepository userRepository;
@Override
@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return loadUserByEmail(username);
}
private UserDetails loadUserByEmail(final String email) | throws EmailNotFoundException { |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/unusedspringsecurity/UserDetailsServiceImpl.java | // Path: src/main/java/yourwebproject2/framework/exception/EmailNotFoundException.java
// public class EmailNotFoundException extends AuthenticationException {
// public EmailNotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/User.java
// @Entity
// @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
// @Table(indexes = { @Index(name="email_idx", columnList = "email", unique = true),
// @Index(name="displayName_idx", columnList = "display_name") })
// public class User extends JPAEntity<Long> implements Serializable {
// public enum Role {
// USER,
// ADMIN
// }
//
// private String email;
// private @JsonIgnore String password;
// private boolean enabled;
// private Role role;
// private String displayName;
//
// private @JsonIgnore Integer loginCount;
// private Date currentLoginAt;
// private Date lastLoginAt;
// private @JsonIgnore String currentLoginIp;
// private @JsonIgnore String lastLoginIp;
//
// private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//
// @Column @Email @NotNull @NotBlank
// public String getEmail() {
// return this.email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// @JsonIgnore @Column(nullable = false, length = 60)
// public String getPassword() {
// return this.password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Column(nullable = false)
// public boolean isEnabled() {
// return this.enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// @Column(nullable = false)
// public Role getRole() {
// return this.role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// @Column(name="display_name")
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// @JsonIgnore @Column
// public Integer getLoginCount() {
// return loginCount;
// }
//
// public void setLoginCount(Integer loginCount) {
// this.loginCount = loginCount;
// }
//
// @Column
// public Date getCurrentLoginAt() {
// return currentLoginAt;
// }
//
// public void setCurrentLoginAt(Date currentLoginAt) {
// this.currentLoginAt = currentLoginAt;
// }
//
// @Column
// public Date getLastLoginAt() {
// return lastLoginAt;
// }
//
// public void setLastLoginAt(Date lastLoginAt) {
// this.lastLoginAt = lastLoginAt;
// }
//
// @JsonIgnore @Column
// public String getCurrentLoginIp() {
// return currentLoginIp;
// }
//
// public void setCurrentLoginIp(String currentLoginIp) {
// this.currentLoginIp = currentLoginIp;
// }
//
// @JsonIgnore @Column
// public String getLastLoginIp() {
// return lastLoginIp;
// }
//
// public void setLastLoginIp(String lastLoginIp) {
// this.lastLoginIp = lastLoginIp;
// }
//
// /**
// * Method to create the hash of the password before storing
// *
// * @param pass
// *
// * @return SHA hash digest of the password
// */
// public static synchronized String hashPassword(String pass) {
// return passwordEncoder.encode(pass);
// }
//
// public static synchronized boolean doesPasswordMatch(String rawPass, String encodedPass) {
// return passwordEncoder.matches(rawPass, encodedPass);
// }
//
// @Override
// public String toString() {
// return "User{" +
// "email='" + email + '\'' +
// ", password='" + password + '\'' +
// ", enabled=" + enabled +
// ", role=" + role +
// ", displayName='" + displayName + '\'' +
// ", loginCount=" + loginCount +
// ", currentLoginAt=" + currentLoginAt +
// ", lastLoginAt=" + lastLoginAt +
// ", currentLoginIp='" + currentLoginIp + '\'' +
// ", lastLoginIp='" + lastLoginIp + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/UserRepository.java
// public interface UserRepository extends BaseJPARepository<User, Long> {
// /**
// * Finds a user with the given email
// *
// * @param email
// * @return
// */
// public User findByEmail(String email);
// }
| import yourwebproject2.framework.exception.EmailNotFoundException;
import yourwebproject2.model.entity.User;
import yourwebproject2.model.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*; | }
@Override
public String getUsername() {
return null;
}
@Override
public boolean isAccountNonExpired() {
return false;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
}
@Override
public boolean isEnabled() {
return false;
}
};
}
// Converts yourwebproject2.model.entity..User user to org.springframework.security.core.userdetails.User | // Path: src/main/java/yourwebproject2/framework/exception/EmailNotFoundException.java
// public class EmailNotFoundException extends AuthenticationException {
// public EmailNotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/User.java
// @Entity
// @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
// @Table(indexes = { @Index(name="email_idx", columnList = "email", unique = true),
// @Index(name="displayName_idx", columnList = "display_name") })
// public class User extends JPAEntity<Long> implements Serializable {
// public enum Role {
// USER,
// ADMIN
// }
//
// private String email;
// private @JsonIgnore String password;
// private boolean enabled;
// private Role role;
// private String displayName;
//
// private @JsonIgnore Integer loginCount;
// private Date currentLoginAt;
// private Date lastLoginAt;
// private @JsonIgnore String currentLoginIp;
// private @JsonIgnore String lastLoginIp;
//
// private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//
// @Column @Email @NotNull @NotBlank
// public String getEmail() {
// return this.email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// @JsonIgnore @Column(nullable = false, length = 60)
// public String getPassword() {
// return this.password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Column(nullable = false)
// public boolean isEnabled() {
// return this.enabled;
// }
//
// public void setEnabled(boolean enabled) {
// this.enabled = enabled;
// }
//
// @Column(nullable = false)
// public Role getRole() {
// return this.role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// @Column(name="display_name")
// public String getDisplayName() {
// return displayName;
// }
//
// public void setDisplayName(String displayName) {
// this.displayName = displayName;
// }
//
// @JsonIgnore @Column
// public Integer getLoginCount() {
// return loginCount;
// }
//
// public void setLoginCount(Integer loginCount) {
// this.loginCount = loginCount;
// }
//
// @Column
// public Date getCurrentLoginAt() {
// return currentLoginAt;
// }
//
// public void setCurrentLoginAt(Date currentLoginAt) {
// this.currentLoginAt = currentLoginAt;
// }
//
// @Column
// public Date getLastLoginAt() {
// return lastLoginAt;
// }
//
// public void setLastLoginAt(Date lastLoginAt) {
// this.lastLoginAt = lastLoginAt;
// }
//
// @JsonIgnore @Column
// public String getCurrentLoginIp() {
// return currentLoginIp;
// }
//
// public void setCurrentLoginIp(String currentLoginIp) {
// this.currentLoginIp = currentLoginIp;
// }
//
// @JsonIgnore @Column
// public String getLastLoginIp() {
// return lastLoginIp;
// }
//
// public void setLastLoginIp(String lastLoginIp) {
// this.lastLoginIp = lastLoginIp;
// }
//
// /**
// * Method to create the hash of the password before storing
// *
// * @param pass
// *
// * @return SHA hash digest of the password
// */
// public static synchronized String hashPassword(String pass) {
// return passwordEncoder.encode(pass);
// }
//
// public static synchronized boolean doesPasswordMatch(String rawPass, String encodedPass) {
// return passwordEncoder.matches(rawPass, encodedPass);
// }
//
// @Override
// public String toString() {
// return "User{" +
// "email='" + email + '\'' +
// ", password='" + password + '\'' +
// ", enabled=" + enabled +
// ", role=" + role +
// ", displayName='" + displayName + '\'' +
// ", loginCount=" + loginCount +
// ", currentLoginAt=" + currentLoginAt +
// ", lastLoginAt=" + lastLoginAt +
// ", currentLoginIp='" + currentLoginIp + '\'' +
// ", lastLoginIp='" + lastLoginIp + '\'' +
// '}';
// }
// }
//
// Path: src/main/java/yourwebproject2/model/repository/UserRepository.java
// public interface UserRepository extends BaseJPARepository<User, Long> {
// /**
// * Finds a user with the given email
// *
// * @param email
// * @return
// */
// public User findByEmail(String email);
// }
// Path: src/main/java/yourwebproject2/unusedspringsecurity/UserDetailsServiceImpl.java
import yourwebproject2.framework.exception.EmailNotFoundException;
import yourwebproject2.model.entity.User;
import yourwebproject2.model.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
}
@Override
public String getUsername() {
return null;
}
@Override
public boolean isAccountNonExpired() {
return false;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
}
@Override
public boolean isEnabled() {
return false;
}
};
}
// Converts yourwebproject2.model.entity..User user to org.springframework.security.core.userdetails.User | private org.springframework.security.core.userdetails.User buildUserForAuthentication(User user, |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/unusedspringsecurity/RESTAuthFilter.java | // Path: src/main/java/yourwebproject2/service/UserService.java
// public interface UserService extends BaseService<User, Long> {
//
// /**
// * Register a new user into the system
// *
// * @param user
// * @param request
// *
// * @return
// */
// public User registerUser(User user, HttpServletRequest request);
//
//
// /**
// * Login a new user into the system
// *
// * @param user
// * @param request
// *
// * @return
// */
// public User loginUser(User user, HttpServletRequest request);
//
//
// /**
// * Method to validate whether the given password
// * is same as users password stored in the system
// *
// * @param user
// * @param pass
// *
// * @return
// */
// public boolean isValidPass(User user, String pass);
//
//
// /**
// * Validates whether the given email already
// * exists in the system.
// *
// * @param email
// *
// * @return
// */
// public boolean isEmailExists(String email);
//
//
// /**
// * Finds a user entity by the given email
// *
// * @param email
// * @return
// */
// public User findByEmail(String email) throws EmailNotFoundException;
// }
| import yourwebproject2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; | package yourwebproject2.unusedspringsecurity;
/**
* @author: kameshr
*/
public class RESTAuthFilter extends OncePerRequestFilter {
@Autowired | // Path: src/main/java/yourwebproject2/service/UserService.java
// public interface UserService extends BaseService<User, Long> {
//
// /**
// * Register a new user into the system
// *
// * @param user
// * @param request
// *
// * @return
// */
// public User registerUser(User user, HttpServletRequest request);
//
//
// /**
// * Login a new user into the system
// *
// * @param user
// * @param request
// *
// * @return
// */
// public User loginUser(User user, HttpServletRequest request);
//
//
// /**
// * Method to validate whether the given password
// * is same as users password stored in the system
// *
// * @param user
// * @param pass
// *
// * @return
// */
// public boolean isValidPass(User user, String pass);
//
//
// /**
// * Validates whether the given email already
// * exists in the system.
// *
// * @param email
// *
// * @return
// */
// public boolean isEmailExists(String email);
//
//
// /**
// * Finds a user entity by the given email
// *
// * @param email
// * @return
// */
// public User findByEmail(String email) throws EmailNotFoundException;
// }
// Path: src/main/java/yourwebproject2/unusedspringsecurity/RESTAuthFilter.java
import yourwebproject2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
package yourwebproject2.unusedspringsecurity;
/**
* @author: kameshr
*/
public class RESTAuthFilter extends OncePerRequestFilter {
@Autowired | private UserService userService; |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/core/JobExecutionThread.java | // Path: src/main/java/yourwebproject2/model/entity/Job.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="status_idx", columnList = "status"),
// @Index(name="category_idx", columnList = "category")})
// public class Job extends JPAEntity<Long> {
// public enum Status {
// NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL
// }
//
// private String name;
// private String metadataJson;
// private String callbackUrl;
// private Date submitTime;
// private Status status;
// private Date scheduledTime;
// private Date completionTime;
// private Integer retryCount;
// private Category category;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Column
// public String getCallbackUrl() {
// return callbackUrl;
// }
//
// public void setCallbackUrl(String callbackUrl) {
// this.callbackUrl = callbackUrl;
// }
//
// @Column
// public String getMetadataJson() {
// return metadataJson;
// }
//
// public void setMetadataJson(String metadataJson) {
// this.metadataJson = metadataJson;
// }
//
// @NotNull
// @Column
// public Date getSubmitTime() {
// return submitTime;
// }
//
// public void setSubmitTime(Date submitTime) {
// this.submitTime = submitTime;
// }
//
// @OneToOne(fetch = FetchType.EAGER)
// public Category getCategory() {
// return category;
// }
//
// public void setCategory(Category category) {
// this.category = category;
// }
//
// @NotNull
// @Column
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// @Column
// public Date getScheduledTime() {
// return scheduledTime;
// }
//
// public void setScheduledTime(Date scheduledTime) {
// this.scheduledTime = scheduledTime;
// }
//
// @Column
// public Date getCompletionTime() {
// return completionTime;
// }
//
// public void setCompletionTime(Date completionTime) {
// this.completionTime = completionTime;
// }
//
// @Column
// public Integer getRetryCount() {
// return retryCount;
// }
//
// public void setRetryCount(Integer retryCount) {
// this.retryCount = retryCount;
// }
//
// @Override
// public String toString() {
// return "Job{" +
// "name='" + name + '\'' +
// ", metadataJson='" + metadataJson + '\'' +
// ", callbackUrl='" + callbackUrl + '\'' +
// ", submitTime=" + submitTime +
// ", status=" + status +
// ", scheduledTime=" + scheduledTime +
// ", completionTime=" + completionTime +
// ", retryCount=" + retryCount +
// ", category=" + category +
// '}';
// }
// }
| import yourwebproject2.model.entity.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.concurrent.Callable; | package yourwebproject2.core;
/**
* Created by Y.Kamesh on 8/2/2015.
*/
public class JobExecutionThread implements Callable {
private static Logger LOG = LoggerFactory.getLogger(JobExecutionThread.class); | // Path: src/main/java/yourwebproject2/model/entity/Job.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="status_idx", columnList = "status"),
// @Index(name="category_idx", columnList = "category")})
// public class Job extends JPAEntity<Long> {
// public enum Status {
// NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL
// }
//
// private String name;
// private String metadataJson;
// private String callbackUrl;
// private Date submitTime;
// private Status status;
// private Date scheduledTime;
// private Date completionTime;
// private Integer retryCount;
// private Category category;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Column
// public String getCallbackUrl() {
// return callbackUrl;
// }
//
// public void setCallbackUrl(String callbackUrl) {
// this.callbackUrl = callbackUrl;
// }
//
// @Column
// public String getMetadataJson() {
// return metadataJson;
// }
//
// public void setMetadataJson(String metadataJson) {
// this.metadataJson = metadataJson;
// }
//
// @NotNull
// @Column
// public Date getSubmitTime() {
// return submitTime;
// }
//
// public void setSubmitTime(Date submitTime) {
// this.submitTime = submitTime;
// }
//
// @OneToOne(fetch = FetchType.EAGER)
// public Category getCategory() {
// return category;
// }
//
// public void setCategory(Category category) {
// this.category = category;
// }
//
// @NotNull
// @Column
// public Status getStatus() {
// return status;
// }
//
// public void setStatus(Status status) {
// this.status = status;
// }
//
// @Column
// public Date getScheduledTime() {
// return scheduledTime;
// }
//
// public void setScheduledTime(Date scheduledTime) {
// this.scheduledTime = scheduledTime;
// }
//
// @Column
// public Date getCompletionTime() {
// return completionTime;
// }
//
// public void setCompletionTime(Date completionTime) {
// this.completionTime = completionTime;
// }
//
// @Column
// public Integer getRetryCount() {
// return retryCount;
// }
//
// public void setRetryCount(Integer retryCount) {
// this.retryCount = retryCount;
// }
//
// @Override
// public String toString() {
// return "Job{" +
// "name='" + name + '\'' +
// ", metadataJson='" + metadataJson + '\'' +
// ", callbackUrl='" + callbackUrl + '\'' +
// ", submitTime=" + submitTime +
// ", status=" + status +
// ", scheduledTime=" + scheduledTime +
// ", completionTime=" + completionTime +
// ", retryCount=" + retryCount +
// ", category=" + category +
// '}';
// }
// }
// Path: src/main/java/yourwebproject2/core/JobExecutionThread.java
import yourwebproject2.model.entity.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.concurrent.Callable;
package yourwebproject2.core;
/**
* Created by Y.Kamesh on 8/2/2015.
*/
public class JobExecutionThread implements Callable {
private static Logger LOG = LoggerFactory.getLogger(JobExecutionThread.class); | private Job job; |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/service/CategoryService.java | // Path: src/main/java/yourwebproject2/framework/data/BaseService.java
// public interface BaseService<T extends Entity, ID extends Serializable> {
// /**
// * Method to setup the service with basic
// * required data. Called after Spring initialization.
// */
// public void setupService();
//
// /**
// * Service to insert the new object
// *
// * @param object
// * The newly object
// */
// public T insert(T object) throws Exception;
//
// /**
// * Service to update an existing object
// *
// * @param object
// * The existing object
// */
// public T update(T object) throws Exception;
//
// /**
// * Service to delete an existing object
// *
// * @param object
// * The existing object
// */
// public void delete(T object) throws Exception;
//
// /**
// * Service to find an existing object by its given id and query name
// *
// * @param id
// * Id of the resource
// */
// public T findById(ID id) throws Exception;
//
//
// /**
// * Service to find a collection of entities by pages
// *
// * @param pageNum
// * @param countPerPage
// * @param order
// *
// * @return
// *
// * @throws Exception
// */
// public Collection<T> findAllByPage(int pageNum, int countPerPage, Order order) throws Exception;
// }
//
// Path: src/main/java/yourwebproject2/framework/exception/NotFoundException.java
// public class NotFoundException extends Exception {
// public NotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/Category.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="priority_idx", columnList = "priority"),
// @Index(name="parentCategory_idx", columnList = "parent_category")})
// public class Category extends JPAEntity<Long> {
// private String name;
// private Integer priority;
// private Category parentCategory;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @NotNull
// @Column
// public Integer getPriority() {
// return priority;
// }
//
// public void setPriority(Integer priority) {
// this.priority = priority;
// }
//
// @ManyToOne(fetch = FetchType.EAGER)
// public Category getParentCategory() {
// return parentCategory;
// }
//
// public void setParentCategory(Category parentCategory) {
// this.parentCategory = parentCategory;
// }
//
// @Override
// public String toString() {
// return "Category{" +
// "name='" + name + '\'' +
// ", priority=" + priority +
// ", parentCategory=" + parentCategory +
// '}';
// }
// }
| import yourwebproject2.framework.data.BaseService;
import yourwebproject2.framework.exception.NotFoundException;
import yourwebproject2.model.entity.Category;
import java.util.List; | package yourwebproject2.service;
/**
* Brings in the basic CRUD service ops from BaseService. Insert additional ops here.
*
* Created by Y.Kamesh on 8/2/2015.
*/
public interface CategoryService extends BaseService<Category, Long> {
/**
* Validates whether the given category already
* exists in the system.
*
* @param categoryName
*
* @return
*/
public boolean isCategoryPresent(String categoryName);
/**
* Validates whether the given category priority already
* exists in the system.
*
* @param priorityId
*
* @return
*/
public boolean isPriorityPresent(Integer priorityId);
/**
* Find category by name
*
* @param categoryName
* @return
*/ | // Path: src/main/java/yourwebproject2/framework/data/BaseService.java
// public interface BaseService<T extends Entity, ID extends Serializable> {
// /**
// * Method to setup the service with basic
// * required data. Called after Spring initialization.
// */
// public void setupService();
//
// /**
// * Service to insert the new object
// *
// * @param object
// * The newly object
// */
// public T insert(T object) throws Exception;
//
// /**
// * Service to update an existing object
// *
// * @param object
// * The existing object
// */
// public T update(T object) throws Exception;
//
// /**
// * Service to delete an existing object
// *
// * @param object
// * The existing object
// */
// public void delete(T object) throws Exception;
//
// /**
// * Service to find an existing object by its given id and query name
// *
// * @param id
// * Id of the resource
// */
// public T findById(ID id) throws Exception;
//
//
// /**
// * Service to find a collection of entities by pages
// *
// * @param pageNum
// * @param countPerPage
// * @param order
// *
// * @return
// *
// * @throws Exception
// */
// public Collection<T> findAllByPage(int pageNum, int countPerPage, Order order) throws Exception;
// }
//
// Path: src/main/java/yourwebproject2/framework/exception/NotFoundException.java
// public class NotFoundException extends Exception {
// public NotFoundException(String message) {
// super(message);
// }
// }
//
// Path: src/main/java/yourwebproject2/model/entity/Category.java
// @Entity
// @Table(indexes = { @Index(name="name_idx", columnList = "name", unique = true),
// @Index(name="priority_idx", columnList = "priority"),
// @Index(name="parentCategory_idx", columnList = "parent_category")})
// public class Category extends JPAEntity<Long> {
// private String name;
// private Integer priority;
// private Category parentCategory;
//
// @NotNull @NotBlank
// @Column
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @NotNull
// @Column
// public Integer getPriority() {
// return priority;
// }
//
// public void setPriority(Integer priority) {
// this.priority = priority;
// }
//
// @ManyToOne(fetch = FetchType.EAGER)
// public Category getParentCategory() {
// return parentCategory;
// }
//
// public void setParentCategory(Category parentCategory) {
// this.parentCategory = parentCategory;
// }
//
// @Override
// public String toString() {
// return "Category{" +
// "name='" + name + '\'' +
// ", priority=" + priority +
// ", parentCategory=" + parentCategory +
// '}';
// }
// }
// Path: src/main/java/yourwebproject2/service/CategoryService.java
import yourwebproject2.framework.data.BaseService;
import yourwebproject2.framework.exception.NotFoundException;
import yourwebproject2.model.entity.Category;
import java.util.List;
package yourwebproject2.service;
/**
* Brings in the basic CRUD service ops from BaseService. Insert additional ops here.
*
* Created by Y.Kamesh on 8/2/2015.
*/
public interface CategoryService extends BaseService<Category, Long> {
/**
* Validates whether the given category already
* exists in the system.
*
* @param categoryName
*
* @return
*/
public boolean isCategoryPresent(String categoryName);
/**
* Validates whether the given category priority already
* exists in the system.
*
* @param priorityId
*
* @return
*/
public boolean isPriorityPresent(Integer priorityId);
/**
* Find category by name
*
* @param categoryName
* @return
*/ | public Category findByCategoryName(String categoryName) throws NotFoundException; |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/auth/JWTTokenAuthFilter.java | // Path: src/main/java/yourwebproject2/service/UserService.java
// public interface UserService extends BaseService<User, Long> {
//
// /**
// * Register a new user into the system
// *
// * @param user
// * @param request
// *
// * @return
// */
// public User registerUser(User user, HttpServletRequest request);
//
//
// /**
// * Login a new user into the system
// *
// * @param user
// * @param request
// *
// * @return
// */
// public User loginUser(User user, HttpServletRequest request);
//
//
// /**
// * Method to validate whether the given password
// * is same as users password stored in the system
// *
// * @param user
// * @param pass
// *
// * @return
// */
// public boolean isValidPass(User user, String pass);
//
//
// /**
// * Validates whether the given email already
// * exists in the system.
// *
// * @param email
// *
// * @return
// */
// public boolean isEmailExists(String email);
//
//
// /**
// * Finds a user entity by the given email
// *
// * @param email
// * @return
// */
// public User findByEmail(String email) throws EmailNotFoundException;
// }
| import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import yourwebproject2.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern; | package yourwebproject2.auth;
/**
* @author: kameshr
*/
public class JWTTokenAuthFilter extends OncePerRequestFilter {
private static List<Pattern> AUTH_ROUTES = new ArrayList<>();
private static List<String> NO_AUTH_ROUTES = new ArrayList<>();
public static final String JWT_KEY = "JWT-TOKEN-SECRET";
static {
AUTH_ROUTES.add(Pattern.compile("/api/*"));
NO_AUTH_ROUTES.add("/api/user/authenticate");
NO_AUTH_ROUTES.add("/api/user/register");
}
private Logger LOG = LoggerFactory.getLogger(JWTTokenAuthFilter.class);
@Autowired | // Path: src/main/java/yourwebproject2/service/UserService.java
// public interface UserService extends BaseService<User, Long> {
//
// /**
// * Register a new user into the system
// *
// * @param user
// * @param request
// *
// * @return
// */
// public User registerUser(User user, HttpServletRequest request);
//
//
// /**
// * Login a new user into the system
// *
// * @param user
// * @param request
// *
// * @return
// */
// public User loginUser(User user, HttpServletRequest request);
//
//
// /**
// * Method to validate whether the given password
// * is same as users password stored in the system
// *
// * @param user
// * @param pass
// *
// * @return
// */
// public boolean isValidPass(User user, String pass);
//
//
// /**
// * Validates whether the given email already
// * exists in the system.
// *
// * @param email
// *
// * @return
// */
// public boolean isEmailExists(String email);
//
//
// /**
// * Finds a user entity by the given email
// *
// * @param email
// * @return
// */
// public User findByEmail(String email) throws EmailNotFoundException;
// }
// Path: src/main/java/yourwebproject2/auth/JWTTokenAuthFilter.java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import yourwebproject2.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
package yourwebproject2.auth;
/**
* @author: kameshr
*/
public class JWTTokenAuthFilter extends OncePerRequestFilter {
private static List<Pattern> AUTH_ROUTES = new ArrayList<>();
private static List<String> NO_AUTH_ROUTES = new ArrayList<>();
public static final String JWT_KEY = "JWT-TOKEN-SECRET";
static {
AUTH_ROUTES.add(Pattern.compile("/api/*"));
NO_AUTH_ROUTES.add("/api/user/authenticate");
NO_AUTH_ROUTES.add("/api/user/register");
}
private Logger LOG = LoggerFactory.getLogger(JWTTokenAuthFilter.class);
@Autowired | private UserService userService; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.