I am trying to collect 2 data fields from the list object.
I am using Employee object:
public class Employee
{
private long id;
private Source source;
private String name;
private String gender;
// getters
private Builder toBuilder(Builder builder)
{
builder.id = this.summaryDataId;
builder.name = this.name;
builder.gender = this.gender;
builder.source = this.source;
return builder;
}
getting employee data into a list in a service class
final List<Employee> employeeData = employeeDao.retrieveEmployeeData(emp.getID());
and then trying to create a list with employeeId and sourceid (Ex: 1234:3). for this I am trying to use collectors.toList
List<String> employeeCollector = employeeData.stream()
.filter(s -> s.getId != null)
.filter(s -> s.getSource() != null && s.getSource().getId() != null)
.collect(Collectors.toList());
how do i get employeeid:souceid format using collectors.toLis()
You just need an intermediate operation map to extract the employee id and source id
List<String> employeeCollector = employeeData.stream()
.filter(s -> s.getId != null)
.filter(s -> s.getSource() != null && s.getSource().getId() != null)
.map(s-> String.format("%s:%s",s.getId(),s.getSource().getId()))
.collect(Collectors.toList());
Related
I have following following DAO query method
#Query("SELECT * FROM user_level_insights WHERE organization_id = :orgId AND user_id = :userId")
fun getInsightsByUserId1(orgId: String, userId: String, builder: (BoundStatementBuilder) -> BoundStatementBuilder): PagingIterable<UserLevelInsights>
Specifically I am trying to specify some statement attributes (at the end it should be paging state).
I am trying to test this DAO using following code
val iterable = controller.userLevelInsightsDao.getInsightsByUserId2(
basicInsight.organizationId,
basicInsight.userId
) { builder -> builder.setPageSize(1) }
Unfortunately this call fails with
java.lang.IllegalArgumentException: builder is not a variable in this bound statement
And when I look into autogenerated code for DAO interface I see following
public PagingIterable<UserLevelInsights> getInsightsByUserId1(String orgId, String userId,
Function1<? super BoundStatementBuilder, ? extends BoundStatementBuilder> builder) {
BoundStatementBuilder boundStatementBuilder = getInsightsByUserId1Statement.boundStatementBuilder();
NullSavingStrategy nullSavingStrategy = NullSavingStrategy.DO_NOT_SET;
if (orgId != null || nullSavingStrategy == NullSavingStrategy.SET_TO_NULL) {
boundStatementBuilder = boundStatementBuilder.set("orgId", orgId, String.class);
}
if (userId != null || nullSavingStrategy == NullSavingStrategy.SET_TO_NULL) {
boundStatementBuilder = boundStatementBuilder.set("userId", userId, String.class);
}
if (builder != null || nullSavingStrategy == NullSavingStrategy.SET_TO_NULL) {
boundStatementBuilder = boundStatementBuilder.set("builder", builder, GENERIC_TYPE);
}
BoundStatement boundStatement = boundStatementBuilder.build();
return executeAndMapToEntityIterable(boundStatement, userLevelInsightsHelper);
}
Which looks wrong to me - builder is really is not a field on bound statement.
So my question is what am I doing wrong defining builder lambda?
I'm trying to develop music player, I've made a loader and adapter for my data retreiving from mediastore, but when I call query from my app it only returns one row, I don't know wat's wrong with my code, would u help me fixing that problem?
That's my loader which should return a list I'll use in another place
public static List<Song> getAllArtistSongs(Context context, long artist_id){
List<Song> ArtistSongList = new ArrayList<>();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = new String[]{
"_id",
"title",
"album_id",
"album",
"artist",
"duration",
"track"
};
String sortorder = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
String selection = "is_music=1 and artist_id="+artist_id;
Cursor cursor = context.getContentResolver().query(uri, projection, selection, null, sortorder);
assert cursor != null;
if (cursor.moveToFirst()) {
do {
int trackNumber = cursor.getInt(6);
while (trackNumber >= 1000) {
trackNumber -= 1000;
}
Long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
Long albumid = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
String albumname = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
String artistname = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
ArtistSongList.add(new Song(id, title, albumid, albumname, artist_id, artistname, duration, trackNumber));
} while (cursor.moveToNext());
cursor.close();
}
return ArtistSongList;
}
And this is the adapter which I use to bind to a recyclerview
public void onBindViewHolder(#NonNull VH holder, int position) {
Song song = artistSongList.get(position);
if(song!=null){
holder.ttv.setText(song.title);
holder.dtv.setText(song.artistName);
int trackN = song.trackNumber;
if(trackN==0){
holder.ntv.setText("_");
}else holder.ntv.setText(String.valueOf(trackN));
}
}
And this is where I call the query func
private void setupAlbumList() {
System.out.println(artistId);
songList = ArtistSongLoader.getAllArtistSongs(getActivity(), artistId);
adapter = new ArtistSongAdapter(getActivity(), songList);
recy.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
recy.setAdapter(new ArtistSongAdapter(getActivity(), songList));
}
Thx in advance for helping
My example to retrieve all tracks:
private final String track_id = MediaStore.Audio.Media._ID;
private final String track_no = MediaStore.Audio.Media.TRACK;
private final String track_name = MediaStore.Audio.Media.TITLE;
private final String artist = MediaStore.Audio.Media.ARTIST;
private final String artist_id = MediaStore.Audio.Media.ARTIST_ID;
private final String duration = MediaStore.Audio.Media.DURATION;
private final String album = MediaStore.Audio.Media.ALBUM;
private final String composer = MediaStore.Audio.Media.COMPOSER;
private final String year = MediaStore.Audio.Media.YEAR;
private final String path = MediaStore.Audio.Media.DATA;
private final String date_added = MediaStore.Audio.Media.DATE_ADDED;
public Cursor getAllTracks(Context context) {
// gets all tracks
if (context != null) {
ContentResolver cr = context.getContentResolver();
final String[] columns = {track_id, track_no, artist, track_name,
album, duration, path, year, composer};
return cr.query(uri, columns, null, null, null);
} else {
return null;
}
}
then you have
String selection = "is_music=1"
first, you do not need is_music=1. For multiple tracks you of course need more than 1 track by the same artist
The adapter is irrelevant, the query does the selection
To return albums for an artist
public Cursor getArtistsAlbumcursor(Context context, String artistId) {
ContentResolver cr = context.getContentResolver();
final String _id = MediaStore.Audio.Media._ID;
final String album_id = MediaStore.Audio.Media.ALBUM_ID;
final String artistid = MediaStore.Audio.Media.ARTIST_ID;
final String[] columns = {_id, album_id, artistid};
if (artistId != null) {
String where = artistid + " =?";
String[] aId = {artistId};
return cr.query(uri, columns, where, aId, null);
} else {
return null;
}
}
For some reason I'm returning 9 rows of duplicate data using this query in my repository.
#Query("select distinct profile from OfficeProfile profile where profile.fcoDesignCd in
(select officeLocation.asccode from OfficeLocation officeLocation, OfficeProfile profile
where officeLocation.statecode = :stateCode and officeLocation.asccode = profile.fcoDesignCd)")
public List<OfficeProfile> searchStateASC(#Param("stateCode") String stateCode);
The sql query that returns 9 distinct rows of data is below. The queries appear to be identical.
select
op.FCO_DESIGN_CD,
op.office_addr_line1,
op.office_addr_line2,
op.office_addr_state,
op.office_addr_zip
from cridba.office_profile op
where op.fco_design_cd in (
select asc_code from cridba.cris_lk_location cll , cridba.office_profile op
where cll.state_code='VA'
and cll.asc_code = op.fco_design_cd);
This is how I'm iterating over the values. I set my debugger and noticed the same 9 values with ids.
for(OfficeProfile locationInfo: officeLocatorRepository.searchStateASC(stateCode))
Here are my entity relationships.
Office Profile (Parent)
#OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "profile")
private Set<OfficeLocation> officeLocation = new HashSet<>(0);
Office Location (Child)
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "asc_code", referencedColumnName = "fco_design_cd", nullable = false, insertable=false,
updatable=false)
public OfficeProfile profile;
I'm overriding equals and hashcode in both classes. Since I'm joining these tables using asc_code do i override that or id? or both? Here is what I have so far.
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OfficeProfile officeProfile = (OfficeProfile) o;
if (officeProfile.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), officeProfile.getId());
}
#Override
public int hashCode() {
return Objects.hashCode(getId());
}
Should I add #Id to fcoDesignCd even though this table already has an id? fcoDesignCd is the referenced column in join?
#Column(name = "fco_design_cd")
private String fcoDesignCd;
HQL output...
select distinct officeprof0_.office_type_id as office_type_id1_1_, ......
from cridba.office_profile officeprof0_ where officeprof0_.fco_design_cd in
(select officeloca1_.asc_code
from cridba.cris_lk_location officeloca1_, cridba.office_profile
officeprof2_ where officeloca1_.state_code=? and
officeloca1_.asc_code=officeprof2_.fco_design_cd)
Does this look like the right path to take? JPA How add unique contraint on column for #OneToMany relation like on username
You shouldn't add another #Id column for your table, since you already have one. Make sure that its backed up with a unique constraint in the database.
The overriding of hashCode and equals looks ok also.
The problem with duplicates is probably in the query.
Hello I have a query and I want the result into list of objects, not entity. But the result is actualy a object which I should transfer to my object. Is there a way to map it directly to my custom object?
Maybe this will help you :
public interface ObjRepository extends JpaRepository<MyObject, Long> {
#Query(value = "FROM MyObject WHERE objname = ?1")
public List<MyObject> findByName(String name);
}
Approach-1: using List of object array.
When using native query, we get list of Object array i.e each row in list is array. Elements in array represent column values.
In repo interface:
#Query(value = "select col1, col2, col3 from table1 where col1 = :key", nativeQuery = true)
List<Object[]> findByKey(#Param("key") String key);
In caller
List<Object[]> objectList = new ArrayList<Object[]>();
objectList = repo.findByKey(key);
List<CustomObject> customObjectList = new ArrayList<>();
for (Object[] tuple : objectList) {
String col1 = (String) tuple[0];
String col2 = (String) tuple[1];
String col3 = (String) tuple[2];
CustomObject obj = new CustomObject();
obj.setCol1(col1);
obj.setCol2(col2);
obj.setCol3(col3);
customObjectList.add(obj);
}
return customObjectList;
Approach-2: using custom dto that represents columns in each row.
Refer https://stackoverflow.com/a/42905382/1358551
final List<MyCustomDTO> statuses = myRepository
.findStatuses(marketId, campaignId, stationIds).stream()
.map(o -> new MyCustomDTO(((BigInteger) o[0]), (Boolean) o[1], (Timestamp) o[2]))
.collect(toList());
public class StationStatusDTO {
private long id;
private boolean isSomething;
private LocalDateTime date;
public MyCustomDTO(BigInteger id, Boolean isSomething, Timestamp date) {
this(id.longValue(),
isSomething,
(date == null) ? null : LocalDateTime
.ofInstant(Instant.ofEpochMilli(date.getTime()),
TimeZone.getDefault().toZoneId()));
}
I have created a custom Calendar, using the <SharePoint:SPCalendarView id=spcalView runat="server"> </SharePoint:SPCalendarView>.
Then I had inserted some events to the Calendar List, and its possible for me to display the events in the view spcalView created above. For this I passed SPListItemCollection(ie retrieved the collection from Calendar List) to a function MakeSchedule().
private SPCalendarItemCollection MakeSchedule(SPListItemCollection calListItems)
{
SPCalendarItemCollection items = new SPCalendarItemCollection();
for (int i = 0; i < calListItems.Count; i++)
{
SPListItem item = calListItems[i];
DateTime StartTime = Convert.ToDateTime(item["EventDate"]);
DateTime EndTime = Convert.ToDateTime(item["EndDate"]);
string appointmentId = "";
if (item["AppointmentID"] != null)
appointmentId = item["AppointmentID"].ToString();
string clientID = "";
if (item["clientID"] != null)
clientID = item["clientID"].ToString();
string Description = "";
if (item["Description"] != null)
Description = item["Description"].ToString();
string Location = "";
if (item["Location"] != null)
Location = item["Location"].ToString();
string Title = "";
if (item["Title"] != null)
Title = item["Title"].ToString();
bool Recurrance = false;
if (item["fRecurrence"] != null)
Recurrance = (bool)item["fRecurrence"];
bool AllDayEvent = false;
if (item["fAllDayEvent"] != null)
AllDayEvent = (bool)item["fAllDayEvent"];
SPWeb web = SPContext.Current.Web;
string relativeURL = web.ServerRelativeUrl;
string absoluteURL = web.Url;
items.Add(
new SPCalendarItem()
{
ItemID = item["ID"].ToString(),
StartDate = StartTime,
EndDate = EndTime,
hasEndDate = true,
Title = Title,
Location = Location,
Description = Description,
IsAllDayEvent = AllDayEvent,
IsRecurrence = Recurrance,
CalendarType = (int)SPCalendarType.Gregorian,
BackgroundColorClassName="ApptCnfirmed",
DisplayFormUrl = relativeURL + "/_layouts/TestProj.Webparts/AppointmentsEdit.aspx"
}
);
}
return items;
}
Here in this for each event item added to the SPCalendarItemCollection, i had set the DisplayFormUrl to an application page. So when i click an event in Spcalendar view,it gets redirected to application page along with the ID of the item clicked as query string.
In the Application page, retrieved the ID, and based on the ID, I retrieved the currentLstItem. but from that i am not able to get the custom fields added by me in the CalendarList.
public partial class AppointmentsEdit : LayoutsPageBase
{
protected void Page_Load(object sender, EventArgs e)
{
string ID = Page.Request.QueryString["ID"].ToString();//this Id is the unique id of the Appointment List
string Source=Page.Request.QueryString["Source"].ToString();
if (ID != "" && ID != null)
{
SPList lstApp = SPContext.Current.Web.Lists["Appointment"];
SPListItem currentLstItem = lstApp.GetItemById(Convert.ToInt32(ID.ToString()));
}
else
{
}
}
}
Is this the proper way to edit the calendar event?, because i have custom fields added to the Calendar List in sharepoint. I tried using designer but i am not able to get the code behind for the EditForm.aspx.
Thanks in advance!!