0% found this document useful (0 votes)
34 views26 pages

Mobile Architecture Practical File (Aditya Kumar)

The document outlines a mobile service architecture for a service request application, detailing the use of React Native for the frontend and Node.js with MongoDB for the backend. It emphasizes scalability, security, and performance through various strategies like JWT authentication, load balancing, and caching with Redis. Additionally, it includes code snippets for a login application, a UI for engineering branches, a RESTful API, and a mobile app that consumes the API and integrates a third-party weather service.

Uploaded by

Sahil Pahuja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views26 pages

Mobile Architecture Practical File (Aditya Kumar)

The document outlines a mobile service architecture for a service request application, detailing the use of React Native for the frontend and Node.js with MongoDB for the backend. It emphasizes scalability, security, and performance through various strategies like JWT authentication, load balancing, and caching with Redis. Additionally, it includes code snippets for a login application, a UI for engineering branches, a RESTful API, and a mobile app that consumes the API and integrates a third-party weather service.

Uploaded by

Sahil Pahuja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Q1.

Design a mobile service architecture for a specific use


case, considering scalability, security, and performance.

Solution:
1. Use Case Overview:
Users: Customers requesting services (e.g., repairs, support).
Service Providers: Technicians fulfilling service requests.
Admin: Managing requests and user data.

2. Architecture:
Frontend (Mobile App):
Platform: React Native (cross-platform support).
Components:
Service request UI.
Login/Authentication (JWT).
Real-time notifications (Firebase).

Backend (API Layer):


Platform: [Link] + Express.
Database: MongoDB (flexible schema).
Authentication: JWT for stateless login.
Real-time Updates: WebSockets for notifications.
Caching: Redis for frequently accessed data.

Security:
HTTPS: For encrypted communication.
JWT: For authentication.
CORS & Rate Limiting: To prevent abuse.
Input Validation: To protect against SQL injection and XSS.

Performance & Scalability:


Load Balancing: NGINX or HAProxy to distribute traffic.
Microservices: For scalability (Authentication, Requests, etc.).
Redis: For caching.
Database Sharding: For scalability if needed.
Auto-scaling: Cloud services for dynamic scaling.

3. High-Level Data Flow:


User Registration/Login: Mobile app communicates with API (POST /register,
POST /login).
Service Request: User creates a request via POST /service-requests.
Service Status Update: Service provider updates request status via PUT /service-
requests/{id}.
Real-time Notifications: WebSockets/FCM sends updates to users.
Q2. Create a login application and open a browser with any
search engine.

Solution: [Link]

import React, { useState } from 'react';


import { View, Text, TextInput, Button, Alert, Linking, StyleSheet } from 'react-native';

// Predefined credentials for demo purposes


const VALID_USERNAME = 'user';
const VALID_PASSWORD = 'password';

const App = () => {


const [username, setUsername] = useState('');
const [password, setPassword] = useState('');

const handleLogin = () => {


if (username === VALID_USERNAME && password === VALID_PASSWORD) {
// Successful login - open the search engine in browser
const searchEngineURL = '[Link]
[Link](searchEngineURL).catch(err => [Link]("Failed to open browser",
[Link]));
} else {
// Show an alert for failed login
[Link]('Login Failed', 'Invalid username or password');
}
};

return (
<View style={[Link]}>
<Text style={[Link]}>Login</Text>

<TextInput
style={[Link]}
placeholder="Username"
value={username}
onChangeText={setUsername}
/>

<TextInput
style={[Link]}
placeholder="Password"
secureTextEntry
value={password}
onChangeText={setPassword}
/>
<Button title="Login" onPress={handleLogin} />
</View>
);
};

const styles = [Link]({


container: {
flex: 1,
justifyContent: 'center',
padding: 16,
backgroundColor: '#f2f2f2',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 24,
},
input: {
height: 40,
borderColor: '#ccc',
borderWidth: 1,
marginBottom: 12,
paddingHorizontal: 8,
},
});

export default App;


Output:

Q3. Create a UI listing the engineering branches. If the user


selects a branch name, display the number of semesters and
subjects in each semester.
Solution: [Link]
import React, { useState } from 'react';
import { View, Text, FlatList, TouchableOpacity, StyleSheet } from 'react-native';

const branches = [
{ name: 'Computer Science', semesters: 8, subjectsPerSemester: [5, 5, 5, 5, 5, 5, 5, 5] },
{ name: 'Mechanical Engineering', semesters: 8, subjectsPerSemester: [6, 6, 6, 6, 5, 5, 5,
5] },
{ name: 'Electrical Engineering', semesters: 8, subjectsPerSemester: [5, 5, 5, 6, 5, 5, 5, 5] },
{ name: 'Civil Engineering', semesters: 8, subjectsPerSemester: [6, 6, 6, 6, 5, 5, 5, 5] },
{ name: 'Electronics Engineering', semesters: 8, subjectsPerSemester: [5, 6, 5, 5, 6, 6, 5, 5]
},
];

const App = () => {


const [selectedBranch, setSelectedBranch] = useState(null);

const renderBranchItem = ({ item }) => (


<TouchableOpacity
style={[Link]}
onPress={() => setSelectedBranch(item)}
>
<Text style={[Link]}>{[Link]}</Text>
</TouchableOpacity>
);

const renderSemesterDetails = () => (


<View style={[Link]}>
<Text style={[Link]}>{[Link]}</Text>
<Text style={[Link]}>Total Semesters: {[Link]}</Text>

{[Link]((subjects, index) => (


<Text key={index} style={[Link]}>
Semester {index + 1}: {subjects} Subjects
</Text>
))}

<TouchableOpacity
style={[Link]}
onPress={() => setSelectedBranch(null)}
>
<Text style={[Link]}>Back to Branches</Text>
</TouchableOpacity>
</View>
);

return (
<View style={[Link]}>
{selectedBranch ? (
renderSemesterDetails()
):(
<>
<Text style={[Link]}>Engineering Branches</Text>
<FlatList
data={branches}
keyExtractor={(item) => [Link]}
renderItem={renderBranchItem}
/>
</>
)}
</View>
);
};

const styles = [Link]({


container: {
flex: 1,
padding: 70,
backgroundColor: '#f2f2f2',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 20,
},
branchItem: {
padding: 15,
backgroundColor: '#4CAF50',
marginVertical: 8,
borderRadius: 5,
},
branchText: {
fontSize: 18,
color: '#fff',
textAlign: 'center',
},
detailsContainer: {
flex: 1,
justifyContent: 'center',
},
branchTitle: {
fontSize: 22,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 15,
},
semesterText: {
fontSize: 16,
textAlign: 'center',
marginBottom: 5,
},
backButton: {
marginTop: 20,
padding: 10,
backgroundColor: '#2196F3',
borderRadius: 5,
alignItems: 'center',
},
backButtonText: {
color: '#fff',
fontSize: 16,
},
});

export default App;

Output:
Q4. Create a RESTful API using [Link] to expose mobile
services.

Solution:
File: [Link]

const express = require('express');


const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();

// Middleware
[Link](cors());
[Link]([Link]());

// Connect to MongoDB (Replace with your database URL)


[Link]('mongodb://localhost:27017/mobileServices')
.then(() => [Link]('Connected to MongoDB...'))
.catch(err => [Link]('Failed to connect to MongoDB:', err));

// Define a Schema (Example: Mobile Service Request)


const serviceRequestSchema = new [Link]({
customerName: String,
serviceType: String,
requestDate: { type: Date, default: [Link] },
status: { type: String, default: 'pending' }
});

// Create a model based on the schema


const ServiceRequest = [Link]('ServiceRequest', serviceRequestSchema);
// API Routes
// Create a new service request
[Link]('/api/service-requests', async (req, res) => {
const { customerName, serviceType } = [Link];
const newRequest = new ServiceRequest({
customerName,
serviceType
});

try {
const savedRequest = await [Link]();
[Link](201).json(savedRequest);
} catch (err) {
[Link](500).json({ error: 'Failed to create service request' });
}
});

// Get all service requests


[Link]('/api/service-requests', async (req, res) => {
try {
const requests = await [Link]();
[Link](200).json(requests);
} catch (err) {
[Link](500).json({ error: 'Failed to fetch service requests' });
}
});

// Get a service request by ID


[Link]('/api/service-requests/:id', async (req, res) => {
const { id } = [Link];

try {
const request = await [Link](id);
if (request) {
[Link](200).json(request);
} else {
[Link](404).json({ error: 'Service request not found' });
}
} catch (err) {
[Link](500).json({ error: 'Failed to fetch service request' });
}
});

// Update the status of a service request


[Link]('/api/service-requests/:id', async (req, res) => {
const { id } = [Link];
const { status } = [Link];
try {
const updatedRequest = await [Link](id, { status }, { new:
true });
if (updatedRequest) {
[Link](200).json(updatedRequest);
} else {
[Link](404).json({ error: 'Service request not found' });
}
} catch (err) {
[Link](500).json({ error: 'Failed to update service request' });
}
});

// Delete a service request


[Link]('/api/service-requests/:id', async (req, res) => {
const { id } = [Link];

try {
const deletedRequest = await [Link](id);
if (deletedRequest) {
[Link](200).json({ message: 'Service request deleted' });
} else {
[Link](404).json({ error: 'Service request not found' });
}
} catch (err) {
[Link](500).json({ error: 'Failed to delete service request' });
}
});

// Start server
const PORT = 5000;
[Link](PORT, () => {
[Link](`Server running on port ${PORT}`);
});
Output:
Q5. Consume a RESTful API from a mobile app using
JavaScript.

Solution:
File: [Link]

import React, { useState, useEffect } from 'react';


import { StyleSheet, Text, TextInput, View, Button, FlatList, TouchableOpacity, Alert } from
'react-native';
import axios from 'axios';

const API_URL = '[Link]

export default function App() {


const [customerName, setCustomerName] = useState('');
const [serviceType, setServiceType] = useState('');
const [requests, setRequests] = useState([]);
const [loading, setLoading] = useState(false);

// Fetch all service requests


const fetchServiceRequests = async () => {
setLoading(true);
try {
const response = await [Link](API_URL);
setRequests([Link]);
} catch (error) {
[Link](error);
[Link]('Error', `${error}`);
} finally {
setLoading(false);
}
};

useEffect(() => {
fetchServiceRequests();
}, []);
// Add a new service request
const addServiceRequest = async () => {
if (!customerName || !serviceType) {
[Link]('Error', 'Please fill in all fields');
return;
}

try {
const response = await [Link](API_URL, { customerName, serviceType });
setRequests([...requests, [Link]]);
setCustomerName('');
setServiceType('');
} catch (error) {
[Link]('Error', 'Failed to create service request');
}
};

// Delete a service request


const deleteServiceRequest = async (id) => {
try {
await [Link](`${API_URL}/${id}`);
setRequests([Link](request => request._id !== id));
} catch (error) {
[Link]('Error', 'Failed to delete service request');
}
};

// Update the status of a service request


const updateStatus = async (id, status) => {
try {
const response = await [Link](`${API_URL}/${id}`, { status });
setRequests([Link](request => request._id === id ? [Link] : request));
} catch (error) {
[Link]('Error', 'Failed to update service request');
}
};

return (
<View style={[Link]}>
<Text style={[Link]}>Service Requests</Text>

<TextInput
style={[Link]}
placeholder="Customer Name"
value={customerName}
onChangeText={setCustomerName}
/>
<TextInput
style={[Link]}
placeholder="Service Type"
value={serviceType}
onChangeText={setServiceType}
/>

<Button title="Add Service Request" onPress={addServiceRequest} />

{loading ? (
<Text>Loading...</Text>
):(
<FlatList
data={requests}
keyExtractor={(item) => item._id}
renderItem={({ item }) => (
<View style={[Link]}>
<Text>{[Link]} - {[Link]}</Text>
<Text>Status: {[Link]}</Text>
<View style={[Link]}>
<Button title="Complete" onPress={() => updateStatus(item._id, 'completed')} />
<Button title="Delete" onPress={() => deleteServiceRequest(item._id)} />
</View>
</View>
)}
/>
)}
</View>
);
}

const styles = [Link]({


container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 16,
marginTop: 35
},
title: {
fontSize: 24,
marginBottom: 20,
fontWeight: 'bold',
},
input: {
width: '80%',
padding: 10,
borderWidth: 1,
marginBottom: 10,
borderRadius: 5,
},
item: {
padding: 10,
borderWidth: 1,
borderRadius: 5,
marginBottom: 10,
width: '80%',
},
buttons: {
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 10,
},
});
Output:

Q6. Integrate a third-party web service into a simple mobile


app.

Solution:
import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';
import axios from 'axios';

const App = () => {


// State variables for city name input and weather data
const [city, setCity] = useState('');
const [weather, setWeather] = useState(null);
const [error, setError] = useState('');

// Function to fetch weather data


const fetchWeatherData = async () => {
// Clear previous data or errors
setWeather(null);
setError('');

try {
const response = await [Link]('[Link] {
params: {
q: city,
appid: 'cb3087c954fad22971361d7a914deb53',
units: 'metric',
},
});
setWeather([Link]);
} catch (err) {
setError('Failed to fetch weather data. Please try again.');
}
};

return (
<View style={[Link]}>
<Text style={[Link]}>Weather App</Text>
<TextInput
style={[Link]}
placeholder="Enter city name"
value={city}
onChangeText={setCity}
/>
<Button title="Get Weather" onPress={fetchWeatherData} />
{weather && (
<View style={[Link]}>
<Text style={[Link]}>City: {[Link]}</Text>
<Text style={[Link]}>Temperature: {[Link]}°C</Text>
<Text style={[Link]}>Weather: {[Link][0].description}</Text>
</View>
)}
{error && <Text style={[Link]}>{error}</Text>}
</View>
);
};

const styles = [Link]({


container: {
flex: 1,
justifyContent: 'center',
padding: 16,
},
title: {
fontSize: 24,
textAlign: 'center',
marginBottom: 16,
},
input: {
borderColor: '#ccc',
borderWidth: 1,
padding: 8,
marginBottom: 16,
borderRadius: 4,
},
result: {
marginTop: 16,
},
resultText: {
fontSize: 16,
marginBottom: 4,
},
error: {
marginTop: 16,
color: 'red',
},
});

export default App;


Output:

Q7. Develop a mobile app using cross-platform framework


Flutter.

Solution:
File : [Link]
import 'package:billionairapp/addordeduct_money.dart';
import 'package:billionairapp/balance_view.dart';
import 'package:flutter/[Link]';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatefulWidget {


const MyApp({[Link]});

@override
State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {


double balance = 0;
void addMoney() async {
setState(() {
balance += 500;
});

// Obtain shared preferences.


final SharedPreferences prefs = await [Link]();

// Save an double value to 'decimal' key.


await [Link]('balance', balance);
}

void deductMoney() async {


setState(() {
if (balance == 0) return;
balance -= 500;
});
// Obtain shared preferences.
final SharedPreferences prefs = await [Link]();

// Save an double value to 'decimal' key.


await [Link]('balance', balance);
}

@override
void initState() {
loadBalance();
[Link]();
}
void loadBalance() async {
// Obtain shared preferences.
final SharedPreferences prefs = await [Link]();

// Try reading data from the 'decimal' key. If it doesn't exist, returns null.
// ?? means that if getDouble has null then set balance to 0 else set balance to stored
value.
setState(() {
balance = [Link]('balance') ?? 0;
});
}

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: [Link](useMaterial3: true),
home: Scaffold(
appBar: AppBar(
backgroundColor: const [Link](255, 40, 46, 51),
centerTitle: true,
title: const Text("Billionaire App!"),
),
body: Container(
padding: const [Link](top: 20, bottom: 20),
height: [Link],
width: [Link],
color: [Link][800],
child: Column(
mainAxisAlignment: [Link],
children: [
BalanceView(balance: balance),
AddOrDeductMoney(addMoney: addMoney, deductMoney: deductMoney)
],
),
)),
);
}
}

File : addordeduct_money.dart

import 'package:flutter/[Link]';

class AddOrDeductMoney extends StatelessWidget {


void Function() addMoney;
void Function() deductMoney;

AddOrDeductMoney({[Link], required [Link], required [Link]});

@override
Widget build(BuildContext context) {
return Expanded(
flex: 2,
child: Row(
mainAxisAlignment: [Link],
children: [
ElevatedButton(
style: [Link](
backgroundColor: [Link][700]),
onPressed: addMoney,
child: const Text(
"Add Money",
style: TextStyle(
fontWeight: [Link],
color: [Link]),
)),
const SizedBox(width: 10),
ElevatedButton(
style: [Link](
backgroundColor: [Link][700]),
onPressed: deductMoney,
child: const Text(
"Withdraw Money",
style: TextStyle(
fontWeight: [Link],
color: [Link]),
),
),
],
));
}
}

File: balance_view.dart
import 'package:flutter/[Link]';
import 'package:intl/[Link]';
// ignore: must_be_immutable
class BalanceView extends StatelessWidget {
double balance = 0;
BalanceView({[Link], required [Link]});

@override
Widget build(BuildContext context) {
return Expanded(
flex: 9,
child: Column(
mainAxisAlignment: [Link],
children: [
const Text(
"Bank Balance : ",
style: TextStyle(fontSize: 20, fontWeight: [Link]),
),
Text(
"₹ ${[Link](name: '').format(balance)}",
style: const TextStyle(fontSize: 32, fontWeight: [Link]),
),
],
),
);
}
}
Output:

Q8. Use OWASP security testing tools to identify vulnerabilities


in the mobile app.

Solution:
Output:

You might also like